pyparsing.py 267 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107
  1. # -*- coding: utf-8 -*-
  2. # module pyparsing.py
  3. #
  4. # Copyright (c) 2003-2019 Paul T. McGuire
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining
  7. # a copy of this software and associated documentation files (the
  8. # "Software"), to deal in the Software without restriction, including
  9. # without limitation the rights to use, copy, modify, merge, publish,
  10. # distribute, sublicense, and/or sell copies of the Software, and to
  11. # permit persons to whom the Software is furnished to do so, subject to
  12. # the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be
  15. # included in all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  20. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  21. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  22. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  23. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. #
  25. __doc__ = \
  26. """
  27. pyparsing module - Classes and methods to define and execute parsing grammars
  28. =============================================================================
  29. The pyparsing module is an alternative approach to creating and
  30. executing simple grammars, vs. the traditional lex/yacc approach, or the
  31. use of regular expressions. With pyparsing, you don't need to learn
  32. a new syntax for defining grammars or matching expressions - the parsing
  33. module provides a library of classes that you use to construct the
  34. grammar directly in Python.
  35. Here is a program to parse "Hello, World!" (or any greeting of the form
  36. ``"<salutation>, <addressee>!"``), built up using :class:`Word`,
  37. :class:`Literal`, and :class:`And` elements
  38. (the :class:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,
  39. and the strings are auto-converted to :class:`Literal` expressions)::
  40. from pip._vendor.pyparsing import Word, alphas
  41. # define grammar of a greeting
  42. greet = Word(alphas) + "," + Word(alphas) + "!"
  43. hello = "Hello, World!"
  44. print (hello, "->", greet.parseString(hello))
  45. The program outputs the following::
  46. Hello, World! -> ['Hello', ',', 'World', '!']
  47. The Python representation of the grammar is quite readable, owing to the
  48. self-explanatory class names, and the use of '+', '|' and '^' operators.
  49. The :class:`ParseResults` object returned from
  50. :class:`ParserElement.parseString` can be
  51. accessed as a nested list, a dictionary, or an object with named
  52. attributes.
  53. The pyparsing module handles some of the problems that are typically
  54. vexing when writing text parsers:
  55. - extra or missing whitespace (the above program will also handle
  56. "Hello,World!", "Hello , World !", etc.)
  57. - quoted strings
  58. - embedded comments
  59. Getting Started -
  60. -----------------
  61. Visit the classes :class:`ParserElement` and :class:`ParseResults` to
  62. see the base classes that most other pyparsing
  63. classes inherit from. Use the docstrings for examples of how to:
  64. - construct literal match expressions from :class:`Literal` and
  65. :class:`CaselessLiteral` classes
  66. - construct character word-group expressions using the :class:`Word`
  67. class
  68. - see how to create repetitive expressions using :class:`ZeroOrMore`
  69. and :class:`OneOrMore` classes
  70. - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,
  71. and :class:`'&'<Each>` operators to combine simple expressions into
  72. more complex ones
  73. - associate names with your parsed results using
  74. :class:`ParserElement.setResultsName`
  75. - access the parsed data, which is returned as a :class:`ParseResults`
  76. object
  77. - find some helpful expression short-cuts like :class:`delimitedList`
  78. and :class:`oneOf`
  79. - find more useful common expressions in the :class:`pyparsing_common`
  80. namespace class
  81. """
  82. __version__ = "2.4.7"
  83. __versionTime__ = "30 Mar 2020 00:43 UTC"
  84. __author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
  85. import string
  86. from weakref import ref as wkref
  87. import copy
  88. import sys
  89. import warnings
  90. import re
  91. import sre_constants
  92. import collections
  93. import pprint
  94. import traceback
  95. import types
  96. from datetime import datetime
  97. from operator import itemgetter
  98. import itertools
  99. from functools import wraps
  100. from contextlib import contextmanager
  101. try:
  102. # Python 3
  103. from itertools import filterfalse
  104. except ImportError:
  105. from itertools import ifilterfalse as filterfalse
  106. try:
  107. from _thread import RLock
  108. except ImportError:
  109. from threading import RLock
  110. try:
  111. # Python 3
  112. from collections.abc import Iterable
  113. from collections.abc import MutableMapping, Mapping
  114. except ImportError:
  115. # Python 2.7
  116. from collections import Iterable
  117. from collections import MutableMapping, Mapping
  118. try:
  119. from collections import OrderedDict as _OrderedDict
  120. except ImportError:
  121. try:
  122. from ordereddict import OrderedDict as _OrderedDict
  123. except ImportError:
  124. _OrderedDict = None
  125. try:
  126. from types import SimpleNamespace
  127. except ImportError:
  128. class SimpleNamespace: pass
  129. # version compatibility configuration
  130. __compat__ = SimpleNamespace()
  131. __compat__.__doc__ = """
  132. A cross-version compatibility configuration for pyparsing features that will be
  133. released in a future version. By setting values in this configuration to True,
  134. those features can be enabled in prior versions for compatibility development
  135. and testing.
  136. - collect_all_And_tokens - flag to enable fix for Issue #63 that fixes erroneous grouping
  137. of results names when an And expression is nested within an Or or MatchFirst; set to
  138. True to enable bugfix released in pyparsing 2.3.0, or False to preserve
  139. pre-2.3.0 handling of named results
  140. """
  141. __compat__.collect_all_And_tokens = True
  142. __diag__ = SimpleNamespace()
  143. __diag__.__doc__ = """
  144. Diagnostic configuration (all default to False)
  145. - warn_multiple_tokens_in_named_alternation - flag to enable warnings when a results
  146. name is defined on a MatchFirst or Or expression with one or more And subexpressions
  147. (only warns if __compat__.collect_all_And_tokens is False)
  148. - warn_ungrouped_named_tokens_in_collection - flag to enable warnings when a results
  149. name is defined on a containing expression with ungrouped subexpressions that also
  150. have results names
  151. - warn_name_set_on_empty_Forward - flag to enable warnings whan a Forward is defined
  152. with a results name, but has no contents defined
  153. - warn_on_multiple_string_args_to_oneof - flag to enable warnings whan oneOf is
  154. incorrectly called with multiple str arguments
  155. - enable_debug_on_named_expressions - flag to auto-enable debug on all subsequent
  156. calls to ParserElement.setName()
  157. """
  158. __diag__.warn_multiple_tokens_in_named_alternation = False
  159. __diag__.warn_ungrouped_named_tokens_in_collection = False
  160. __diag__.warn_name_set_on_empty_Forward = False
  161. __diag__.warn_on_multiple_string_args_to_oneof = False
  162. __diag__.enable_debug_on_named_expressions = False
  163. __diag__._all_names = [nm for nm in vars(__diag__) if nm.startswith("enable_") or nm.startswith("warn_")]
  164. def _enable_all_warnings():
  165. __diag__.warn_multiple_tokens_in_named_alternation = True
  166. __diag__.warn_ungrouped_named_tokens_in_collection = True
  167. __diag__.warn_name_set_on_empty_Forward = True
  168. __diag__.warn_on_multiple_string_args_to_oneof = True
  169. __diag__.enable_all_warnings = _enable_all_warnings
  170. __all__ = ['__version__', '__versionTime__', '__author__', '__compat__', '__diag__',
  171. 'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
  172. 'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
  173. 'PrecededBy', 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
  174. 'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
  175. 'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
  176. 'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter',
  177. 'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore', 'Char',
  178. 'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
  179. 'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
  180. 'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
  181. 'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno',
  182. 'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
  183. 'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
  184. 'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
  185. 'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
  186. 'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
  187. 'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation', 'locatedExpr', 'withClass',
  188. 'CloseMatch', 'tokenMap', 'pyparsing_common', 'pyparsing_unicode', 'unicode_set',
  189. 'conditionAsParseAction', 're',
  190. ]
  191. system_version = tuple(sys.version_info)[:3]
  192. PY_3 = system_version[0] == 3
  193. if PY_3:
  194. _MAX_INT = sys.maxsize
  195. basestring = str
  196. unichr = chr
  197. unicode = str
  198. _ustr = str
  199. # build list of single arg builtins, that can be used as parse actions
  200. singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
  201. else:
  202. _MAX_INT = sys.maxint
  203. range = xrange
  204. def _ustr(obj):
  205. """Drop-in replacement for str(obj) that tries to be Unicode
  206. friendly. It first tries str(obj). If that fails with
  207. a UnicodeEncodeError, then it tries unicode(obj). It then
  208. < returns the unicode object | encodes it with the default
  209. encoding | ... >.
  210. """
  211. if isinstance(obj, unicode):
  212. return obj
  213. try:
  214. # If this works, then _ustr(obj) has the same behaviour as str(obj), so
  215. # it won't break any existing code.
  216. return str(obj)
  217. except UnicodeEncodeError:
  218. # Else encode it
  219. ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
  220. xmlcharref = Regex(r'&#\d+;')
  221. xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
  222. return xmlcharref.transformString(ret)
  223. # build list of single arg builtins, tolerant of Python version, that can be used as parse actions
  224. singleArgBuiltins = []
  225. import __builtin__
  226. for fname in "sum len sorted reversed list tuple set any all min max".split():
  227. try:
  228. singleArgBuiltins.append(getattr(__builtin__, fname))
  229. except AttributeError:
  230. continue
  231. _generatorType = type((y for y in range(1)))
  232. def _xml_escape(data):
  233. """Escape &, <, >, ", ', etc. in a string of data."""
  234. # ampersand must be replaced first
  235. from_symbols = '&><"\''
  236. to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split())
  237. for from_, to_ in zip(from_symbols, to_symbols):
  238. data = data.replace(from_, to_)
  239. return data
  240. alphas = string.ascii_uppercase + string.ascii_lowercase
  241. nums = "0123456789"
  242. hexnums = nums + "ABCDEFabcdef"
  243. alphanums = alphas + nums
  244. _bslash = chr(92)
  245. printables = "".join(c for c in string.printable if c not in string.whitespace)
  246. def conditionAsParseAction(fn, message=None, fatal=False):
  247. msg = message if message is not None else "failed user-defined condition"
  248. exc_type = ParseFatalException if fatal else ParseException
  249. fn = _trim_arity(fn)
  250. @wraps(fn)
  251. def pa(s, l, t):
  252. if not bool(fn(s, l, t)):
  253. raise exc_type(s, l, msg)
  254. return pa
  255. class ParseBaseException(Exception):
  256. """base exception class for all parsing runtime exceptions"""
  257. # Performance tuning: we construct a *lot* of these, so keep this
  258. # constructor as small and fast as possible
  259. def __init__(self, pstr, loc=0, msg=None, elem=None):
  260. self.loc = loc
  261. if msg is None:
  262. self.msg = pstr
  263. self.pstr = ""
  264. else:
  265. self.msg = msg
  266. self.pstr = pstr
  267. self.parserElement = elem
  268. self.args = (pstr, loc, msg)
  269. @classmethod
  270. def _from_exception(cls, pe):
  271. """
  272. internal factory method to simplify creating one type of ParseException
  273. from another - avoids having __init__ signature conflicts among subclasses
  274. """
  275. return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
  276. def __getattr__(self, aname):
  277. """supported attributes by name are:
  278. - lineno - returns the line number of the exception text
  279. - col - returns the column number of the exception text
  280. - line - returns the line containing the exception text
  281. """
  282. if aname == "lineno":
  283. return lineno(self.loc, self.pstr)
  284. elif aname in ("col", "column"):
  285. return col(self.loc, self.pstr)
  286. elif aname == "line":
  287. return line(self.loc, self.pstr)
  288. else:
  289. raise AttributeError(aname)
  290. def __str__(self):
  291. if self.pstr:
  292. if self.loc >= len(self.pstr):
  293. foundstr = ', found end of text'
  294. else:
  295. foundstr = (', found %r' % self.pstr[self.loc:self.loc + 1]).replace(r'\\', '\\')
  296. else:
  297. foundstr = ''
  298. return ("%s%s (at char %d), (line:%d, col:%d)" %
  299. (self.msg, foundstr, self.loc, self.lineno, self.column))
  300. def __repr__(self):
  301. return _ustr(self)
  302. def markInputline(self, markerString=">!<"):
  303. """Extracts the exception line from the input string, and marks
  304. the location of the exception with a special symbol.
  305. """
  306. line_str = self.line
  307. line_column = self.column - 1
  308. if markerString:
  309. line_str = "".join((line_str[:line_column],
  310. markerString, line_str[line_column:]))
  311. return line_str.strip()
  312. def __dir__(self):
  313. return "lineno col line".split() + dir(type(self))
  314. class ParseException(ParseBaseException):
  315. """
  316. Exception thrown when parse expressions don't match class;
  317. supported attributes by name are:
  318. - lineno - returns the line number of the exception text
  319. - col - returns the column number of the exception text
  320. - line - returns the line containing the exception text
  321. Example::
  322. try:
  323. Word(nums).setName("integer").parseString("ABC")
  324. except ParseException as pe:
  325. print(pe)
  326. print("column: {}".format(pe.col))
  327. prints::
  328. Expected integer (at char 0), (line:1, col:1)
  329. column: 1
  330. """
  331. @staticmethod
  332. def explain(exc, depth=16):
  333. """
  334. Method to take an exception and translate the Python internal traceback into a list
  335. of the pyparsing expressions that caused the exception to be raised.
  336. Parameters:
  337. - exc - exception raised during parsing (need not be a ParseException, in support
  338. of Python exceptions that might be raised in a parse action)
  339. - depth (default=16) - number of levels back in the stack trace to list expression
  340. and function names; if None, the full stack trace names will be listed; if 0, only
  341. the failing input line, marker, and exception string will be shown
  342. Returns a multi-line string listing the ParserElements and/or function names in the
  343. exception's stack trace.
  344. Note: the diagnostic output will include string representations of the expressions
  345. that failed to parse. These representations will be more helpful if you use `setName` to
  346. give identifiable names to your expressions. Otherwise they will use the default string
  347. forms, which may be cryptic to read.
  348. explain() is only supported under Python 3.
  349. """
  350. import inspect
  351. if depth is None:
  352. depth = sys.getrecursionlimit()
  353. ret = []
  354. if isinstance(exc, ParseBaseException):
  355. ret.append(exc.line)
  356. ret.append(' ' * (exc.col - 1) + '^')
  357. ret.append("{0}: {1}".format(type(exc).__name__, exc))
  358. if depth > 0:
  359. callers = inspect.getinnerframes(exc.__traceback__, context=depth)
  360. seen = set()
  361. for i, ff in enumerate(callers[-depth:]):
  362. frm = ff[0]
  363. f_self = frm.f_locals.get('self', None)
  364. if isinstance(f_self, ParserElement):
  365. if frm.f_code.co_name not in ('parseImpl', '_parseNoCache'):
  366. continue
  367. if f_self in seen:
  368. continue
  369. seen.add(f_self)
  370. self_type = type(f_self)
  371. ret.append("{0}.{1} - {2}".format(self_type.__module__,
  372. self_type.__name__,
  373. f_self))
  374. elif f_self is not None:
  375. self_type = type(f_self)
  376. ret.append("{0}.{1}".format(self_type.__module__,
  377. self_type.__name__))
  378. else:
  379. code = frm.f_code
  380. if code.co_name in ('wrapper', '<module>'):
  381. continue
  382. ret.append("{0}".format(code.co_name))
  383. depth -= 1
  384. if not depth:
  385. break
  386. return '\n'.join(ret)
  387. class ParseFatalException(ParseBaseException):
  388. """user-throwable exception thrown when inconsistent parse content
  389. is found; stops all parsing immediately"""
  390. pass
  391. class ParseSyntaxException(ParseFatalException):
  392. """just like :class:`ParseFatalException`, but thrown internally
  393. when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
  394. that parsing is to stop immediately because an unbacktrackable
  395. syntax error has been found.
  396. """
  397. pass
  398. #~ class ReparseException(ParseBaseException):
  399. #~ """Experimental class - parse actions can raise this exception to cause
  400. #~ pyparsing to reparse the input string:
  401. #~ - with a modified input string, and/or
  402. #~ - with a modified start location
  403. #~ Set the values of the ReparseException in the constructor, and raise the
  404. #~ exception in a parse action to cause pyparsing to use the new string/location.
  405. #~ Setting the values as None causes no change to be made.
  406. #~ """
  407. #~ def __init_( self, newstring, restartLoc ):
  408. #~ self.newParseText = newstring
  409. #~ self.reparseLoc = restartLoc
  410. class RecursiveGrammarException(Exception):
  411. """exception thrown by :class:`ParserElement.validate` if the
  412. grammar could be improperly recursive
  413. """
  414. def __init__(self, parseElementList):
  415. self.parseElementTrace = parseElementList
  416. def __str__(self):
  417. return "RecursiveGrammarException: %s" % self.parseElementTrace
  418. class _ParseResultsWithOffset(object):
  419. def __init__(self, p1, p2):
  420. self.tup = (p1, p2)
  421. def __getitem__(self, i):
  422. return self.tup[i]
  423. def __repr__(self):
  424. return repr(self.tup[0])
  425. def setOffset(self, i):
  426. self.tup = (self.tup[0], i)
  427. class ParseResults(object):
  428. """Structured parse results, to provide multiple means of access to
  429. the parsed data:
  430. - as a list (``len(results)``)
  431. - by list index (``results[0], results[1]``, etc.)
  432. - by attribute (``results.<resultsName>`` - see :class:`ParserElement.setResultsName`)
  433. Example::
  434. integer = Word(nums)
  435. date_str = (integer.setResultsName("year") + '/'
  436. + integer.setResultsName("month") + '/'
  437. + integer.setResultsName("day"))
  438. # equivalent form:
  439. # date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  440. # parseString returns a ParseResults object
  441. result = date_str.parseString("1999/12/31")
  442. def test(s, fn=repr):
  443. print("%s -> %s" % (s, fn(eval(s))))
  444. test("list(result)")
  445. test("result[0]")
  446. test("result['month']")
  447. test("result.day")
  448. test("'month' in result")
  449. test("'minutes' in result")
  450. test("result.dump()", str)
  451. prints::
  452. list(result) -> ['1999', '/', '12', '/', '31']
  453. result[0] -> '1999'
  454. result['month'] -> '12'
  455. result.day -> '31'
  456. 'month' in result -> True
  457. 'minutes' in result -> False
  458. result.dump() -> ['1999', '/', '12', '/', '31']
  459. - day: 31
  460. - month: 12
  461. - year: 1999
  462. """
  463. def __new__(cls, toklist=None, name=None, asList=True, modal=True):
  464. if isinstance(toklist, cls):
  465. return toklist
  466. retobj = object.__new__(cls)
  467. retobj.__doinit = True
  468. return retobj
  469. # Performance tuning: we construct a *lot* of these, so keep this
  470. # constructor as small and fast as possible
  471. def __init__(self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance):
  472. if self.__doinit:
  473. self.__doinit = False
  474. self.__name = None
  475. self.__parent = None
  476. self.__accumNames = {}
  477. self.__asList = asList
  478. self.__modal = modal
  479. if toklist is None:
  480. toklist = []
  481. if isinstance(toklist, list):
  482. self.__toklist = toklist[:]
  483. elif isinstance(toklist, _generatorType):
  484. self.__toklist = list(toklist)
  485. else:
  486. self.__toklist = [toklist]
  487. self.__tokdict = dict()
  488. if name is not None and name:
  489. if not modal:
  490. self.__accumNames[name] = 0
  491. if isinstance(name, int):
  492. name = _ustr(name) # will always return a str, but use _ustr for consistency
  493. self.__name = name
  494. if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None, '', [])):
  495. if isinstance(toklist, basestring):
  496. toklist = [toklist]
  497. if asList:
  498. if isinstance(toklist, ParseResults):
  499. self[name] = _ParseResultsWithOffset(ParseResults(toklist.__toklist), 0)
  500. else:
  501. self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0)
  502. self[name].__name = name
  503. else:
  504. try:
  505. self[name] = toklist[0]
  506. except (KeyError, TypeError, IndexError):
  507. self[name] = toklist
  508. def __getitem__(self, i):
  509. if isinstance(i, (int, slice)):
  510. return self.__toklist[i]
  511. else:
  512. if i not in self.__accumNames:
  513. return self.__tokdict[i][-1][0]
  514. else:
  515. return ParseResults([v[0] for v in self.__tokdict[i]])
  516. def __setitem__(self, k, v, isinstance=isinstance):
  517. if isinstance(v, _ParseResultsWithOffset):
  518. self.__tokdict[k] = self.__tokdict.get(k, list()) + [v]
  519. sub = v[0]
  520. elif isinstance(k, (int, slice)):
  521. self.__toklist[k] = v
  522. sub = v
  523. else:
  524. self.__tokdict[k] = self.__tokdict.get(k, list()) + [_ParseResultsWithOffset(v, 0)]
  525. sub = v
  526. if isinstance(sub, ParseResults):
  527. sub.__parent = wkref(self)
  528. def __delitem__(self, i):
  529. if isinstance(i, (int, slice)):
  530. mylen = len(self.__toklist)
  531. del self.__toklist[i]
  532. # convert int to slice
  533. if isinstance(i, int):
  534. if i < 0:
  535. i += mylen
  536. i = slice(i, i + 1)
  537. # get removed indices
  538. removed = list(range(*i.indices(mylen)))
  539. removed.reverse()
  540. # fixup indices in token dictionary
  541. for name, occurrences in self.__tokdict.items():
  542. for j in removed:
  543. for k, (value, position) in enumerate(occurrences):
  544. occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
  545. else:
  546. del self.__tokdict[i]
  547. def __contains__(self, k):
  548. return k in self.__tokdict
  549. def __len__(self):
  550. return len(self.__toklist)
  551. def __bool__(self):
  552. return (not not self.__toklist)
  553. __nonzero__ = __bool__
  554. def __iter__(self):
  555. return iter(self.__toklist)
  556. def __reversed__(self):
  557. return iter(self.__toklist[::-1])
  558. def _iterkeys(self):
  559. if hasattr(self.__tokdict, "iterkeys"):
  560. return self.__tokdict.iterkeys()
  561. else:
  562. return iter(self.__tokdict)
  563. def _itervalues(self):
  564. return (self[k] for k in self._iterkeys())
  565. def _iteritems(self):
  566. return ((k, self[k]) for k in self._iterkeys())
  567. if PY_3:
  568. keys = _iterkeys
  569. """Returns an iterator of all named result keys."""
  570. values = _itervalues
  571. """Returns an iterator of all named result values."""
  572. items = _iteritems
  573. """Returns an iterator of all named result key-value tuples."""
  574. else:
  575. iterkeys = _iterkeys
  576. """Returns an iterator of all named result keys (Python 2.x only)."""
  577. itervalues = _itervalues
  578. """Returns an iterator of all named result values (Python 2.x only)."""
  579. iteritems = _iteritems
  580. """Returns an iterator of all named result key-value tuples (Python 2.x only)."""
  581. def keys(self):
  582. """Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x)."""
  583. return list(self.iterkeys())
  584. def values(self):
  585. """Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x)."""
  586. return list(self.itervalues())
  587. def items(self):
  588. """Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x)."""
  589. return list(self.iteritems())
  590. def haskeys(self):
  591. """Since keys() returns an iterator, this method is helpful in bypassing
  592. code that looks for the existence of any defined results names."""
  593. return bool(self.__tokdict)
  594. def pop(self, *args, **kwargs):
  595. """
  596. Removes and returns item at specified index (default= ``last``).
  597. Supports both ``list`` and ``dict`` semantics for ``pop()``. If
  598. passed no argument or an integer argument, it will use ``list``
  599. semantics and pop tokens from the list of parsed tokens. If passed
  600. a non-integer argument (most likely a string), it will use ``dict``
  601. semantics and pop the corresponding value from any defined results
  602. names. A second default return value argument is supported, just as in
  603. ``dict.pop()``.
  604. Example::
  605. def remove_first(tokens):
  606. tokens.pop(0)
  607. print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
  608. print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
  609. label = Word(alphas)
  610. patt = label("LABEL") + OneOrMore(Word(nums))
  611. print(patt.parseString("AAB 123 321").dump())
  612. # Use pop() in a parse action to remove named result (note that corresponding value is not
  613. # removed from list form of results)
  614. def remove_LABEL(tokens):
  615. tokens.pop("LABEL")
  616. return tokens
  617. patt.addParseAction(remove_LABEL)
  618. print(patt.parseString("AAB 123 321").dump())
  619. prints::
  620. ['AAB', '123', '321']
  621. - LABEL: AAB
  622. ['AAB', '123', '321']
  623. """
  624. if not args:
  625. args = [-1]
  626. for k, v in kwargs.items():
  627. if k == 'default':
  628. args = (args[0], v)
  629. else:
  630. raise TypeError("pop() got an unexpected keyword argument '%s'" % k)
  631. if (isinstance(args[0], int)
  632. or len(args) == 1
  633. or args[0] in self):
  634. index = args[0]
  635. ret = self[index]
  636. del self[index]
  637. return ret
  638. else:
  639. defaultvalue = args[1]
  640. return defaultvalue
  641. def get(self, key, defaultValue=None):
  642. """
  643. Returns named result matching the given key, or if there is no
  644. such name, then returns the given ``defaultValue`` or ``None`` if no
  645. ``defaultValue`` is specified.
  646. Similar to ``dict.get()``.
  647. Example::
  648. integer = Word(nums)
  649. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  650. result = date_str.parseString("1999/12/31")
  651. print(result.get("year")) # -> '1999'
  652. print(result.get("hour", "not specified")) # -> 'not specified'
  653. print(result.get("hour")) # -> None
  654. """
  655. if key in self:
  656. return self[key]
  657. else:
  658. return defaultValue
  659. def insert(self, index, insStr):
  660. """
  661. Inserts new element at location index in the list of parsed tokens.
  662. Similar to ``list.insert()``.
  663. Example::
  664. print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
  665. # use a parse action to insert the parse location in the front of the parsed results
  666. def insert_locn(locn, tokens):
  667. tokens.insert(0, locn)
  668. print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
  669. """
  670. self.__toklist.insert(index, insStr)
  671. # fixup indices in token dictionary
  672. for name, occurrences in self.__tokdict.items():
  673. for k, (value, position) in enumerate(occurrences):
  674. occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
  675. def append(self, item):
  676. """
  677. Add single element to end of ParseResults list of elements.
  678. Example::
  679. print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
  680. # use a parse action to compute the sum of the parsed integers, and add it to the end
  681. def append_sum(tokens):
  682. tokens.append(sum(map(int, tokens)))
  683. print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
  684. """
  685. self.__toklist.append(item)
  686. def extend(self, itemseq):
  687. """
  688. Add sequence of elements to end of ParseResults list of elements.
  689. Example::
  690. patt = OneOrMore(Word(alphas))
  691. # use a parse action to append the reverse of the matched strings, to make a palindrome
  692. def make_palindrome(tokens):
  693. tokens.extend(reversed([t[::-1] for t in tokens]))
  694. return ''.join(tokens)
  695. print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
  696. """
  697. if isinstance(itemseq, ParseResults):
  698. self.__iadd__(itemseq)
  699. else:
  700. self.__toklist.extend(itemseq)
  701. def clear(self):
  702. """
  703. Clear all elements and results names.
  704. """
  705. del self.__toklist[:]
  706. self.__tokdict.clear()
  707. def __getattr__(self, name):
  708. try:
  709. return self[name]
  710. except KeyError:
  711. return ""
  712. def __add__(self, other):
  713. ret = self.copy()
  714. ret += other
  715. return ret
  716. def __iadd__(self, other):
  717. if other.__tokdict:
  718. offset = len(self.__toklist)
  719. addoffset = lambda a: offset if a < 0 else a + offset
  720. otheritems = other.__tokdict.items()
  721. otherdictitems = [(k, _ParseResultsWithOffset(v[0], addoffset(v[1])))
  722. for k, vlist in otheritems for v in vlist]
  723. for k, v in otherdictitems:
  724. self[k] = v
  725. if isinstance(v[0], ParseResults):
  726. v[0].__parent = wkref(self)
  727. self.__toklist += other.__toklist
  728. self.__accumNames.update(other.__accumNames)
  729. return self
  730. def __radd__(self, other):
  731. if isinstance(other, int) and other == 0:
  732. # useful for merging many ParseResults using sum() builtin
  733. return self.copy()
  734. else:
  735. # this may raise a TypeError - so be it
  736. return other + self
  737. def __repr__(self):
  738. return "(%s, %s)" % (repr(self.__toklist), repr(self.__tokdict))
  739. def __str__(self):
  740. return '[' + ', '.join(_ustr(i) if isinstance(i, ParseResults) else repr(i) for i in self.__toklist) + ']'
  741. def _asStringList(self, sep=''):
  742. out = []
  743. for item in self.__toklist:
  744. if out and sep:
  745. out.append(sep)
  746. if isinstance(item, ParseResults):
  747. out += item._asStringList()
  748. else:
  749. out.append(_ustr(item))
  750. return out
  751. def asList(self):
  752. """
  753. Returns the parse results as a nested list of matching tokens, all converted to strings.
  754. Example::
  755. patt = OneOrMore(Word(alphas))
  756. result = patt.parseString("sldkj lsdkj sldkj")
  757. # even though the result prints in string-like form, it is actually a pyparsing ParseResults
  758. print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
  759. # Use asList() to create an actual list
  760. result_list = result.asList()
  761. print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
  762. """
  763. return [res.asList() if isinstance(res, ParseResults) else res for res in self.__toklist]
  764. def asDict(self):
  765. """
  766. Returns the named parse results as a nested dictionary.
  767. Example::
  768. integer = Word(nums)
  769. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  770. result = date_str.parseString('12/31/1999')
  771. print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
  772. result_dict = result.asDict()
  773. print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
  774. # even though a ParseResults supports dict-like access, sometime you just need to have a dict
  775. import json
  776. print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
  777. print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
  778. """
  779. if PY_3:
  780. item_fn = self.items
  781. else:
  782. item_fn = self.iteritems
  783. def toItem(obj):
  784. if isinstance(obj, ParseResults):
  785. if obj.haskeys():
  786. return obj.asDict()
  787. else:
  788. return [toItem(v) for v in obj]
  789. else:
  790. return obj
  791. return dict((k, toItem(v)) for k, v in item_fn())
  792. def copy(self):
  793. """
  794. Returns a new copy of a :class:`ParseResults` object.
  795. """
  796. ret = ParseResults(self.__toklist)
  797. ret.__tokdict = dict(self.__tokdict.items())
  798. ret.__parent = self.__parent
  799. ret.__accumNames.update(self.__accumNames)
  800. ret.__name = self.__name
  801. return ret
  802. def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True):
  803. """
  804. (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
  805. """
  806. nl = "\n"
  807. out = []
  808. namedItems = dict((v[1], k) for (k, vlist) in self.__tokdict.items()
  809. for v in vlist)
  810. nextLevelIndent = indent + " "
  811. # collapse out indents if formatting is not desired
  812. if not formatted:
  813. indent = ""
  814. nextLevelIndent = ""
  815. nl = ""
  816. selfTag = None
  817. if doctag is not None:
  818. selfTag = doctag
  819. else:
  820. if self.__name:
  821. selfTag = self.__name
  822. if not selfTag:
  823. if namedItemsOnly:
  824. return ""
  825. else:
  826. selfTag = "ITEM"
  827. out += [nl, indent, "<", selfTag, ">"]
  828. for i, res in enumerate(self.__toklist):
  829. if isinstance(res, ParseResults):
  830. if i in namedItems:
  831. out += [res.asXML(namedItems[i],
  832. namedItemsOnly and doctag is None,
  833. nextLevelIndent,
  834. formatted)]
  835. else:
  836. out += [res.asXML(None,
  837. namedItemsOnly and doctag is None,
  838. nextLevelIndent,
  839. formatted)]
  840. else:
  841. # individual token, see if there is a name for it
  842. resTag = None
  843. if i in namedItems:
  844. resTag = namedItems[i]
  845. if not resTag:
  846. if namedItemsOnly:
  847. continue
  848. else:
  849. resTag = "ITEM"
  850. xmlBodyText = _xml_escape(_ustr(res))
  851. out += [nl, nextLevelIndent, "<", resTag, ">",
  852. xmlBodyText,
  853. "</", resTag, ">"]
  854. out += [nl, indent, "</", selfTag, ">"]
  855. return "".join(out)
  856. def __lookup(self, sub):
  857. for k, vlist in self.__tokdict.items():
  858. for v, loc in vlist:
  859. if sub is v:
  860. return k
  861. return None
  862. def getName(self):
  863. r"""
  864. Returns the results name for this token expression. Useful when several
  865. different expressions might match at a particular location.
  866. Example::
  867. integer = Word(nums)
  868. ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
  869. house_number_expr = Suppress('#') + Word(nums, alphanums)
  870. user_data = (Group(house_number_expr)("house_number")
  871. | Group(ssn_expr)("ssn")
  872. | Group(integer)("age"))
  873. user_info = OneOrMore(user_data)
  874. result = user_info.parseString("22 111-22-3333 #221B")
  875. for item in result:
  876. print(item.getName(), ':', item[0])
  877. prints::
  878. age : 22
  879. ssn : 111-22-3333
  880. house_number : 221B
  881. """
  882. if self.__name:
  883. return self.__name
  884. elif self.__parent:
  885. par = self.__parent()
  886. if par:
  887. return par.__lookup(self)
  888. else:
  889. return None
  890. elif (len(self) == 1
  891. and len(self.__tokdict) == 1
  892. and next(iter(self.__tokdict.values()))[0][1] in (0, -1)):
  893. return next(iter(self.__tokdict.keys()))
  894. else:
  895. return None
  896. def dump(self, indent='', full=True, include_list=True, _depth=0):
  897. """
  898. Diagnostic method for listing out the contents of
  899. a :class:`ParseResults`. Accepts an optional ``indent`` argument so
  900. that this string can be embedded in a nested display of other data.
  901. Example::
  902. integer = Word(nums)
  903. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  904. result = date_str.parseString('12/31/1999')
  905. print(result.dump())
  906. prints::
  907. ['12', '/', '31', '/', '1999']
  908. - day: 1999
  909. - month: 31
  910. - year: 12
  911. """
  912. out = []
  913. NL = '\n'
  914. if include_list:
  915. out.append(indent + _ustr(self.asList()))
  916. else:
  917. out.append('')
  918. if full:
  919. if self.haskeys():
  920. items = sorted((str(k), v) for k, v in self.items())
  921. for k, v in items:
  922. if out:
  923. out.append(NL)
  924. out.append("%s%s- %s: " % (indent, (' ' * _depth), k))
  925. if isinstance(v, ParseResults):
  926. if v:
  927. out.append(v.dump(indent=indent, full=full, include_list=include_list, _depth=_depth + 1))
  928. else:
  929. out.append(_ustr(v))
  930. else:
  931. out.append(repr(v))
  932. elif any(isinstance(vv, ParseResults) for vv in self):
  933. v = self
  934. for i, vv in enumerate(v):
  935. if isinstance(vv, ParseResults):
  936. out.append("\n%s%s[%d]:\n%s%s%s" % (indent,
  937. (' ' * (_depth)),
  938. i,
  939. indent,
  940. (' ' * (_depth + 1)),
  941. vv.dump(indent=indent,
  942. full=full,
  943. include_list=include_list,
  944. _depth=_depth + 1)))
  945. else:
  946. out.append("\n%s%s[%d]:\n%s%s%s" % (indent,
  947. (' ' * (_depth)),
  948. i,
  949. indent,
  950. (' ' * (_depth + 1)),
  951. _ustr(vv)))
  952. return "".join(out)
  953. def pprint(self, *args, **kwargs):
  954. """
  955. Pretty-printer for parsed results as a list, using the
  956. `pprint <https://docs.python.org/3/library/pprint.html>`_ module.
  957. Accepts additional positional or keyword args as defined for
  958. `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
  959. Example::
  960. ident = Word(alphas, alphanums)
  961. num = Word(nums)
  962. func = Forward()
  963. term = ident | num | Group('(' + func + ')')
  964. func <<= ident + Group(Optional(delimitedList(term)))
  965. result = func.parseString("fna a,b,(fnb c,d,200),100")
  966. result.pprint(width=40)
  967. prints::
  968. ['fna',
  969. ['a',
  970. 'b',
  971. ['(', 'fnb', ['c', 'd', '200'], ')'],
  972. '100']]
  973. """
  974. pprint.pprint(self.asList(), *args, **kwargs)
  975. # add support for pickle protocol
  976. def __getstate__(self):
  977. return (self.__toklist,
  978. (self.__tokdict.copy(),
  979. self.__parent is not None and self.__parent() or None,
  980. self.__accumNames,
  981. self.__name))
  982. def __setstate__(self, state):
  983. self.__toklist = state[0]
  984. self.__tokdict, par, inAccumNames, self.__name = state[1]
  985. self.__accumNames = {}
  986. self.__accumNames.update(inAccumNames)
  987. if par is not None:
  988. self.__parent = wkref(par)
  989. else:
  990. self.__parent = None
  991. def __getnewargs__(self):
  992. return self.__toklist, self.__name, self.__asList, self.__modal
  993. def __dir__(self):
  994. return dir(type(self)) + list(self.keys())
  995. @classmethod
  996. def from_dict(cls, other, name=None):
  997. """
  998. Helper classmethod to construct a ParseResults from a dict, preserving the
  999. name-value relations as results names. If an optional 'name' argument is
  1000. given, a nested ParseResults will be returned
  1001. """
  1002. def is_iterable(obj):
  1003. try:
  1004. iter(obj)
  1005. except Exception:
  1006. return False
  1007. else:
  1008. if PY_3:
  1009. return not isinstance(obj, (str, bytes))
  1010. else:
  1011. return not isinstance(obj, basestring)
  1012. ret = cls([])
  1013. for k, v in other.items():
  1014. if isinstance(v, Mapping):
  1015. ret += cls.from_dict(v, name=k)
  1016. else:
  1017. ret += cls([v], name=k, asList=is_iterable(v))
  1018. if name is not None:
  1019. ret = cls([ret], name=name)
  1020. return ret
  1021. MutableMapping.register(ParseResults)
  1022. def col (loc, strg):
  1023. """Returns current column within a string, counting newlines as line separators.
  1024. The first column is number 1.
  1025. Note: the default parsing behavior is to expand tabs in the input string
  1026. before starting the parsing process. See
  1027. :class:`ParserElement.parseString` for more
  1028. information on parsing strings containing ``<TAB>`` s, and suggested
  1029. methods to maintain a consistent view of the parsed string, the parse
  1030. location, and line and column positions within the parsed string.
  1031. """
  1032. s = strg
  1033. return 1 if 0 < loc < len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc)
  1034. def lineno(loc, strg):
  1035. """Returns current line number within a string, counting newlines as line separators.
  1036. The first line is number 1.
  1037. Note - the default parsing behavior is to expand tabs in the input string
  1038. before starting the parsing process. See :class:`ParserElement.parseString`
  1039. for more information on parsing strings containing ``<TAB>`` s, and
  1040. suggested methods to maintain a consistent view of the parsed string, the
  1041. parse location, and line and column positions within the parsed string.
  1042. """
  1043. return strg.count("\n", 0, loc) + 1
  1044. def line(loc, strg):
  1045. """Returns the line of text containing loc within a string, counting newlines as line separators.
  1046. """
  1047. lastCR = strg.rfind("\n", 0, loc)
  1048. nextCR = strg.find("\n", loc)
  1049. if nextCR >= 0:
  1050. return strg[lastCR + 1:nextCR]
  1051. else:
  1052. return strg[lastCR + 1:]
  1053. def _defaultStartDebugAction(instring, loc, expr):
  1054. print(("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % (lineno(loc, instring), col(loc, instring))))
  1055. def _defaultSuccessDebugAction(instring, startloc, endloc, expr, toks):
  1056. print("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
  1057. def _defaultExceptionDebugAction(instring, loc, expr, exc):
  1058. print("Exception raised:" + _ustr(exc))
  1059. def nullDebugAction(*args):
  1060. """'Do-nothing' debug action, to suppress debugging output during parsing."""
  1061. pass
  1062. # Only works on Python 3.x - nonlocal is toxic to Python 2 installs
  1063. #~ 'decorator to trim function calls to match the arity of the target'
  1064. #~ def _trim_arity(func, maxargs=3):
  1065. #~ if func in singleArgBuiltins:
  1066. #~ return lambda s,l,t: func(t)
  1067. #~ limit = 0
  1068. #~ foundArity = False
  1069. #~ def wrapper(*args):
  1070. #~ nonlocal limit,foundArity
  1071. #~ while 1:
  1072. #~ try:
  1073. #~ ret = func(*args[limit:])
  1074. #~ foundArity = True
  1075. #~ return ret
  1076. #~ except TypeError:
  1077. #~ if limit == maxargs or foundArity:
  1078. #~ raise
  1079. #~ limit += 1
  1080. #~ continue
  1081. #~ return wrapper
  1082. # this version is Python 2.x-3.x cross-compatible
  1083. 'decorator to trim function calls to match the arity of the target'
  1084. def _trim_arity(func, maxargs=2):
  1085. if func in singleArgBuiltins:
  1086. return lambda s, l, t: func(t)
  1087. limit = [0]
  1088. foundArity = [False]
  1089. # traceback return data structure changed in Py3.5 - normalize back to plain tuples
  1090. if system_version[:2] >= (3, 5):
  1091. def extract_stack(limit=0):
  1092. # special handling for Python 3.5.0 - extra deep call stack by 1
  1093. offset = -3 if system_version == (3, 5, 0) else -2
  1094. frame_summary = traceback.extract_stack(limit=-offset + limit - 1)[offset]
  1095. return [frame_summary[:2]]
  1096. def extract_tb(tb, limit=0):
  1097. frames = traceback.extract_tb(tb, limit=limit)
  1098. frame_summary = frames[-1]
  1099. return [frame_summary[:2]]
  1100. else:
  1101. extract_stack = traceback.extract_stack
  1102. extract_tb = traceback.extract_tb
  1103. # synthesize what would be returned by traceback.extract_stack at the call to
  1104. # user's parse action 'func', so that we don't incur call penalty at parse time
  1105. LINE_DIFF = 6
  1106. # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND
  1107. # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
  1108. this_line = extract_stack(limit=2)[-1]
  1109. pa_call_line_synth = (this_line[0], this_line[1] + LINE_DIFF)
  1110. def wrapper(*args):
  1111. while 1:
  1112. try:
  1113. ret = func(*args[limit[0]:])
  1114. foundArity[0] = True
  1115. return ret
  1116. except TypeError:
  1117. # re-raise TypeErrors if they did not come from our arity testing
  1118. if foundArity[0]:
  1119. raise
  1120. else:
  1121. try:
  1122. tb = sys.exc_info()[-1]
  1123. if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth:
  1124. raise
  1125. finally:
  1126. try:
  1127. del tb
  1128. except NameError:
  1129. pass
  1130. if limit[0] <= maxargs:
  1131. limit[0] += 1
  1132. continue
  1133. raise
  1134. # copy func name to wrapper for sensible debug output
  1135. func_name = "<parse action>"
  1136. try:
  1137. func_name = getattr(func, '__name__',
  1138. getattr(func, '__class__').__name__)
  1139. except Exception:
  1140. func_name = str(func)
  1141. wrapper.__name__ = func_name
  1142. return wrapper
  1143. class ParserElement(object):
  1144. """Abstract base level parser element class."""
  1145. DEFAULT_WHITE_CHARS = " \n\t\r"
  1146. verbose_stacktrace = False
  1147. @staticmethod
  1148. def setDefaultWhitespaceChars(chars):
  1149. r"""
  1150. Overrides the default whitespace chars
  1151. Example::
  1152. # default whitespace chars are space, <TAB> and newline
  1153. OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
  1154. # change to just treat newline as significant
  1155. ParserElement.setDefaultWhitespaceChars(" \t")
  1156. OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
  1157. """
  1158. ParserElement.DEFAULT_WHITE_CHARS = chars
  1159. @staticmethod
  1160. def inlineLiteralsUsing(cls):
  1161. """
  1162. Set class to be used for inclusion of string literals into a parser.
  1163. Example::
  1164. # default literal class used is Literal
  1165. integer = Word(nums)
  1166. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  1167. date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
  1168. # change to Suppress
  1169. ParserElement.inlineLiteralsUsing(Suppress)
  1170. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  1171. date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
  1172. """
  1173. ParserElement._literalStringClass = cls
  1174. @classmethod
  1175. def _trim_traceback(cls, tb):
  1176. while tb.tb_next:
  1177. tb = tb.tb_next
  1178. return tb
  1179. def __init__(self, savelist=False):
  1180. self.parseAction = list()
  1181. self.failAction = None
  1182. # ~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
  1183. self.strRepr = None
  1184. self.resultsName = None
  1185. self.saveAsList = savelist
  1186. self.skipWhitespace = True
  1187. self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)
  1188. self.copyDefaultWhiteChars = True
  1189. self.mayReturnEmpty = False # used when checking for left-recursion
  1190. self.keepTabs = False
  1191. self.ignoreExprs = list()
  1192. self.debug = False
  1193. self.streamlined = False
  1194. self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
  1195. self.errmsg = ""
  1196. self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
  1197. self.debugActions = (None, None, None) # custom debug actions
  1198. self.re = None
  1199. self.callPreparse = True # used to avoid redundant calls to preParse
  1200. self.callDuringTry = False
  1201. def copy(self):
  1202. """
  1203. Make a copy of this :class:`ParserElement`. Useful for defining
  1204. different parse actions for the same parsing pattern, using copies of
  1205. the original parse element.
  1206. Example::
  1207. integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
  1208. integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K")
  1209. integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
  1210. print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
  1211. prints::
  1212. [5120, 100, 655360, 268435456]
  1213. Equivalent form of ``expr.copy()`` is just ``expr()``::
  1214. integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
  1215. """
  1216. cpy = copy.copy(self)
  1217. cpy.parseAction = self.parseAction[:]
  1218. cpy.ignoreExprs = self.ignoreExprs[:]
  1219. if self.copyDefaultWhiteChars:
  1220. cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
  1221. return cpy
  1222. def setName(self, name):
  1223. """
  1224. Define name for this expression, makes debugging and exception messages clearer.
  1225. Example::
  1226. Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
  1227. Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
  1228. """
  1229. self.name = name
  1230. self.errmsg = "Expected " + self.name
  1231. if __diag__.enable_debug_on_named_expressions:
  1232. self.setDebug()
  1233. return self
  1234. def setResultsName(self, name, listAllMatches=False):
  1235. """
  1236. Define name for referencing matching tokens as a nested attribute
  1237. of the returned parse results.
  1238. NOTE: this returns a *copy* of the original :class:`ParserElement` object;
  1239. this is so that the client can define a basic element, such as an
  1240. integer, and reference it in multiple places with different names.
  1241. You can also set results names using the abbreviated syntax,
  1242. ``expr("name")`` in place of ``expr.setResultsName("name")``
  1243. - see :class:`__call__`.
  1244. Example::
  1245. date_str = (integer.setResultsName("year") + '/'
  1246. + integer.setResultsName("month") + '/'
  1247. + integer.setResultsName("day"))
  1248. # equivalent form:
  1249. date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
  1250. """
  1251. return self._setResultsName(name, listAllMatches)
  1252. def _setResultsName(self, name, listAllMatches=False):
  1253. newself = self.copy()
  1254. if name.endswith("*"):
  1255. name = name[:-1]
  1256. listAllMatches = True
  1257. newself.resultsName = name
  1258. newself.modalResults = not listAllMatches
  1259. return newself
  1260. def setBreak(self, breakFlag=True):
  1261. """Method to invoke the Python pdb debugger when this element is
  1262. about to be parsed. Set ``breakFlag`` to True to enable, False to
  1263. disable.
  1264. """
  1265. if breakFlag:
  1266. _parseMethod = self._parse
  1267. def breaker(instring, loc, doActions=True, callPreParse=True):
  1268. import pdb
  1269. # this call to pdb.set_trace() is intentional, not a checkin error
  1270. pdb.set_trace()
  1271. return _parseMethod(instring, loc, doActions, callPreParse)
  1272. breaker._originalParseMethod = _parseMethod
  1273. self._parse = breaker
  1274. else:
  1275. if hasattr(self._parse, "_originalParseMethod"):
  1276. self._parse = self._parse._originalParseMethod
  1277. return self
  1278. def setParseAction(self, *fns, **kwargs):
  1279. """
  1280. Define one or more actions to perform when successfully matching parse element definition.
  1281. Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
  1282. ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
  1283. - s = the original string being parsed (see note below)
  1284. - loc = the location of the matching substring
  1285. - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object
  1286. If the functions in fns modify the tokens, they can return them as the return
  1287. value from fn, and the modified list of tokens will replace the original.
  1288. Otherwise, fn does not need to return any value.
  1289. If None is passed as the parse action, all previously added parse actions for this
  1290. expression are cleared.
  1291. Optional keyword arguments:
  1292. - callDuringTry = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing
  1293. Note: the default parsing behavior is to expand tabs in the input string
  1294. before starting the parsing process. See :class:`parseString for more
  1295. information on parsing strings containing ``<TAB>`` s, and suggested
  1296. methods to maintain a consistent view of the parsed string, the parse
  1297. location, and line and column positions within the parsed string.
  1298. Example::
  1299. integer = Word(nums)
  1300. date_str = integer + '/' + integer + '/' + integer
  1301. date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
  1302. # use parse action to convert to ints at parse time
  1303. integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
  1304. date_str = integer + '/' + integer + '/' + integer
  1305. # note that integer fields are now ints, not strings
  1306. date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
  1307. """
  1308. if list(fns) == [None,]:
  1309. self.parseAction = []
  1310. else:
  1311. if not all(callable(fn) for fn in fns):
  1312. raise TypeError("parse actions must be callable")
  1313. self.parseAction = list(map(_trim_arity, list(fns)))
  1314. self.callDuringTry = kwargs.get("callDuringTry", False)
  1315. return self
  1316. def addParseAction(self, *fns, **kwargs):
  1317. """
  1318. Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`.
  1319. See examples in :class:`copy`.
  1320. """
  1321. self.parseAction += list(map(_trim_arity, list(fns)))
  1322. self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
  1323. return self
  1324. def addCondition(self, *fns, **kwargs):
  1325. """Add a boolean predicate function to expression's list of parse actions. See
  1326. :class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
  1327. functions passed to ``addCondition`` need to return boolean success/fail of the condition.
  1328. Optional keyword arguments:
  1329. - message = define a custom message to be used in the raised exception
  1330. - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
  1331. Example::
  1332. integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
  1333. year_int = integer.copy()
  1334. year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
  1335. date_str = year_int + '/' + integer + '/' + integer
  1336. result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
  1337. """
  1338. for fn in fns:
  1339. self.parseAction.append(conditionAsParseAction(fn, message=kwargs.get('message'),
  1340. fatal=kwargs.get('fatal', False)))
  1341. self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
  1342. return self
  1343. def setFailAction(self, fn):
  1344. """Define action to perform if parsing fails at this expression.
  1345. Fail acton fn is a callable function that takes the arguments
  1346. ``fn(s, loc, expr, err)`` where:
  1347. - s = string being parsed
  1348. - loc = location where expression match was attempted and failed
  1349. - expr = the parse expression that failed
  1350. - err = the exception thrown
  1351. The function returns no value. It may throw :class:`ParseFatalException`
  1352. if it is desired to stop parsing immediately."""
  1353. self.failAction = fn
  1354. return self
  1355. def _skipIgnorables(self, instring, loc):
  1356. exprsFound = True
  1357. while exprsFound:
  1358. exprsFound = False
  1359. for e in self.ignoreExprs:
  1360. try:
  1361. while 1:
  1362. loc, dummy = e._parse(instring, loc)
  1363. exprsFound = True
  1364. except ParseException:
  1365. pass
  1366. return loc
  1367. def preParse(self, instring, loc):
  1368. if self.ignoreExprs:
  1369. loc = self._skipIgnorables(instring, loc)
  1370. if self.skipWhitespace:
  1371. wt = self.whiteChars
  1372. instrlen = len(instring)
  1373. while loc < instrlen and instring[loc] in wt:
  1374. loc += 1
  1375. return loc
  1376. def parseImpl(self, instring, loc, doActions=True):
  1377. return loc, []
  1378. def postParse(self, instring, loc, tokenlist):
  1379. return tokenlist
  1380. # ~ @profile
  1381. def _parseNoCache(self, instring, loc, doActions=True, callPreParse=True):
  1382. TRY, MATCH, FAIL = 0, 1, 2
  1383. debugging = (self.debug) # and doActions)
  1384. if debugging or self.failAction:
  1385. # ~ print ("Match", self, "at loc", loc, "(%d, %d)" % (lineno(loc, instring), col(loc, instring)))
  1386. if self.debugActions[TRY]:
  1387. self.debugActions[TRY](instring, loc, self)
  1388. try:
  1389. if callPreParse and self.callPreparse:
  1390. preloc = self.preParse(instring, loc)
  1391. else:
  1392. preloc = loc
  1393. tokensStart = preloc
  1394. if self.mayIndexError or preloc >= len(instring):
  1395. try:
  1396. loc, tokens = self.parseImpl(instring, preloc, doActions)
  1397. except IndexError:
  1398. raise ParseException(instring, len(instring), self.errmsg, self)
  1399. else:
  1400. loc, tokens = self.parseImpl(instring, preloc, doActions)
  1401. except Exception as err:
  1402. # ~ print ("Exception raised:", err)
  1403. if self.debugActions[FAIL]:
  1404. self.debugActions[FAIL](instring, tokensStart, self, err)
  1405. if self.failAction:
  1406. self.failAction(instring, tokensStart, self, err)
  1407. raise
  1408. else:
  1409. if callPreParse and self.callPreparse:
  1410. preloc = self.preParse(instring, loc)
  1411. else:
  1412. preloc = loc
  1413. tokensStart = preloc
  1414. if self.mayIndexError or preloc >= len(instring):
  1415. try:
  1416. loc, tokens = self.parseImpl(instring, preloc, doActions)
  1417. except IndexError:
  1418. raise ParseException(instring, len(instring), self.errmsg, self)
  1419. else:
  1420. loc, tokens = self.parseImpl(instring, preloc, doActions)
  1421. tokens = self.postParse(instring, loc, tokens)
  1422. retTokens = ParseResults(tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults)
  1423. if self.parseAction and (doActions or self.callDuringTry):
  1424. if debugging:
  1425. try:
  1426. for fn in self.parseAction:
  1427. try:
  1428. tokens = fn(instring, tokensStart, retTokens)
  1429. except IndexError as parse_action_exc:
  1430. exc = ParseException("exception raised in parse action")
  1431. exc.__cause__ = parse_action_exc
  1432. raise exc
  1433. if tokens is not None and tokens is not retTokens:
  1434. retTokens = ParseResults(tokens,
  1435. self.resultsName,
  1436. asList=self.saveAsList and isinstance(tokens, (ParseResults, list)),
  1437. modal=self.modalResults)
  1438. except Exception as err:
  1439. # ~ print "Exception raised in user parse action:", err
  1440. if self.debugActions[FAIL]:
  1441. self.debugActions[FAIL](instring, tokensStart, self, err)
  1442. raise
  1443. else:
  1444. for fn in self.parseAction:
  1445. try:
  1446. tokens = fn(instring, tokensStart, retTokens)
  1447. except IndexError as parse_action_exc:
  1448. exc = ParseException("exception raised in parse action")
  1449. exc.__cause__ = parse_action_exc
  1450. raise exc
  1451. if tokens is not None and tokens is not retTokens:
  1452. retTokens = ParseResults(tokens,
  1453. self.resultsName,
  1454. asList=self.saveAsList and isinstance(tokens, (ParseResults, list)),
  1455. modal=self.modalResults)
  1456. if debugging:
  1457. # ~ print ("Matched", self, "->", retTokens.asList())
  1458. if self.debugActions[MATCH]:
  1459. self.debugActions[MATCH](instring, tokensStart, loc, self, retTokens)
  1460. return loc, retTokens
  1461. def tryParse(self, instring, loc):
  1462. try:
  1463. return self._parse(instring, loc, doActions=False)[0]
  1464. except ParseFatalException:
  1465. raise ParseException(instring, loc, self.errmsg, self)
  1466. def canParseNext(self, instring, loc):
  1467. try:
  1468. self.tryParse(instring, loc)
  1469. except (ParseException, IndexError):
  1470. return False
  1471. else:
  1472. return True
  1473. class _UnboundedCache(object):
  1474. def __init__(self):
  1475. cache = {}
  1476. self.not_in_cache = not_in_cache = object()
  1477. def get(self, key):
  1478. return cache.get(key, not_in_cache)
  1479. def set(self, key, value):
  1480. cache[key] = value
  1481. def clear(self):
  1482. cache.clear()
  1483. def cache_len(self):
  1484. return len(cache)
  1485. self.get = types.MethodType(get, self)
  1486. self.set = types.MethodType(set, self)
  1487. self.clear = types.MethodType(clear, self)
  1488. self.__len__ = types.MethodType(cache_len, self)
  1489. if _OrderedDict is not None:
  1490. class _FifoCache(object):
  1491. def __init__(self, size):
  1492. self.not_in_cache = not_in_cache = object()
  1493. cache = _OrderedDict()
  1494. def get(self, key):
  1495. return cache.get(key, not_in_cache)
  1496. def set(self, key, value):
  1497. cache[key] = value
  1498. while len(cache) > size:
  1499. try:
  1500. cache.popitem(False)
  1501. except KeyError:
  1502. pass
  1503. def clear(self):
  1504. cache.clear()
  1505. def cache_len(self):
  1506. return len(cache)
  1507. self.get = types.MethodType(get, self)
  1508. self.set = types.MethodType(set, self)
  1509. self.clear = types.MethodType(clear, self)
  1510. self.__len__ = types.MethodType(cache_len, self)
  1511. else:
  1512. class _FifoCache(object):
  1513. def __init__(self, size):
  1514. self.not_in_cache = not_in_cache = object()
  1515. cache = {}
  1516. key_fifo = collections.deque([], size)
  1517. def get(self, key):
  1518. return cache.get(key, not_in_cache)
  1519. def set(self, key, value):
  1520. cache[key] = value
  1521. while len(key_fifo) > size:
  1522. cache.pop(key_fifo.popleft(), None)
  1523. key_fifo.append(key)
  1524. def clear(self):
  1525. cache.clear()
  1526. key_fifo.clear()
  1527. def cache_len(self):
  1528. return len(cache)
  1529. self.get = types.MethodType(get, self)
  1530. self.set = types.MethodType(set, self)
  1531. self.clear = types.MethodType(clear, self)
  1532. self.__len__ = types.MethodType(cache_len, self)
  1533. # argument cache for optimizing repeated calls when backtracking through recursive expressions
  1534. packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail
  1535. packrat_cache_lock = RLock()
  1536. packrat_cache_stats = [0, 0]
  1537. # this method gets repeatedly called during backtracking with the same arguments -
  1538. # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
  1539. def _parseCache(self, instring, loc, doActions=True, callPreParse=True):
  1540. HIT, MISS = 0, 1
  1541. lookup = (self, instring, loc, callPreParse, doActions)
  1542. with ParserElement.packrat_cache_lock:
  1543. cache = ParserElement.packrat_cache
  1544. value = cache.get(lookup)
  1545. if value is cache.not_in_cache:
  1546. ParserElement.packrat_cache_stats[MISS] += 1
  1547. try:
  1548. value = self._parseNoCache(instring, loc, doActions, callPreParse)
  1549. except ParseBaseException as pe:
  1550. # cache a copy of the exception, without the traceback
  1551. cache.set(lookup, pe.__class__(*pe.args))
  1552. raise
  1553. else:
  1554. cache.set(lookup, (value[0], value[1].copy()))
  1555. return value
  1556. else:
  1557. ParserElement.packrat_cache_stats[HIT] += 1
  1558. if isinstance(value, Exception):
  1559. raise value
  1560. return value[0], value[1].copy()
  1561. _parse = _parseNoCache
  1562. @staticmethod
  1563. def resetCache():
  1564. ParserElement.packrat_cache.clear()
  1565. ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats)
  1566. _packratEnabled = False
  1567. @staticmethod
  1568. def enablePackrat(cache_size_limit=128):
  1569. """Enables "packrat" parsing, which adds memoizing to the parsing logic.
  1570. Repeated parse attempts at the same string location (which happens
  1571. often in many complex grammars) can immediately return a cached value,
  1572. instead of re-executing parsing/validating code. Memoizing is done of
  1573. both valid results and parsing exceptions.
  1574. Parameters:
  1575. - cache_size_limit - (default= ``128``) - if an integer value is provided
  1576. will limit the size of the packrat cache; if None is passed, then
  1577. the cache size will be unbounded; if 0 is passed, the cache will
  1578. be effectively disabled.
  1579. This speedup may break existing programs that use parse actions that
  1580. have side-effects. For this reason, packrat parsing is disabled when
  1581. you first import pyparsing. To activate the packrat feature, your
  1582. program must call the class method :class:`ParserElement.enablePackrat`.
  1583. For best results, call ``enablePackrat()`` immediately after
  1584. importing pyparsing.
  1585. Example::
  1586. from pip._vendor import pyparsing
  1587. pyparsing.ParserElement.enablePackrat()
  1588. """
  1589. if not ParserElement._packratEnabled:
  1590. ParserElement._packratEnabled = True
  1591. if cache_size_limit is None:
  1592. ParserElement.packrat_cache = ParserElement._UnboundedCache()
  1593. else:
  1594. ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit)
  1595. ParserElement._parse = ParserElement._parseCache
  1596. def parseString(self, instring, parseAll=False):
  1597. """
  1598. Execute the parse expression with the given string.
  1599. This is the main interface to the client code, once the complete
  1600. expression has been built.
  1601. Returns the parsed data as a :class:`ParseResults` object, which may be
  1602. accessed as a list, or as a dict or object with attributes if the given parser
  1603. includes results names.
  1604. If you want the grammar to require that the entire input string be
  1605. successfully parsed, then set ``parseAll`` to True (equivalent to ending
  1606. the grammar with ``StringEnd()``).
  1607. Note: ``parseString`` implicitly calls ``expandtabs()`` on the input string,
  1608. in order to report proper column numbers in parse actions.
  1609. If the input string contains tabs and
  1610. the grammar uses parse actions that use the ``loc`` argument to index into the
  1611. string being parsed, you can ensure you have a consistent view of the input
  1612. string by:
  1613. - calling ``parseWithTabs`` on your grammar before calling ``parseString``
  1614. (see :class:`parseWithTabs`)
  1615. - define your parse action using the full ``(s, loc, toks)`` signature, and
  1616. reference the input string using the parse action's ``s`` argument
  1617. - explictly expand the tabs in your input string before calling
  1618. ``parseString``
  1619. Example::
  1620. Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
  1621. Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
  1622. """
  1623. ParserElement.resetCache()
  1624. if not self.streamlined:
  1625. self.streamline()
  1626. # ~ self.saveAsList = True
  1627. for e in self.ignoreExprs:
  1628. e.streamline()
  1629. if not self.keepTabs:
  1630. instring = instring.expandtabs()
  1631. try:
  1632. loc, tokens = self._parse(instring, 0)
  1633. if parseAll:
  1634. loc = self.preParse(instring, loc)
  1635. se = Empty() + StringEnd()
  1636. se._parse(instring, loc)
  1637. except ParseBaseException as exc:
  1638. if ParserElement.verbose_stacktrace:
  1639. raise
  1640. else:
  1641. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  1642. if getattr(exc, '__traceback__', None) is not None:
  1643. exc.__traceback__ = self._trim_traceback(exc.__traceback__)
  1644. raise exc
  1645. else:
  1646. return tokens
  1647. def scanString(self, instring, maxMatches=_MAX_INT, overlap=False):
  1648. """
  1649. Scan the input string for expression matches. Each match will return the
  1650. matching tokens, start location, and end location. May be called with optional
  1651. ``maxMatches`` argument, to clip scanning after 'n' matches are found. If
  1652. ``overlap`` is specified, then overlapping matches will be reported.
  1653. Note that the start and end locations are reported relative to the string
  1654. being parsed. See :class:`parseString` for more information on parsing
  1655. strings with embedded tabs.
  1656. Example::
  1657. source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
  1658. print(source)
  1659. for tokens, start, end in Word(alphas).scanString(source):
  1660. print(' '*start + '^'*(end-start))
  1661. print(' '*start + tokens[0])
  1662. prints::
  1663. sldjf123lsdjjkf345sldkjf879lkjsfd987
  1664. ^^^^^
  1665. sldjf
  1666. ^^^^^^^
  1667. lsdjjkf
  1668. ^^^^^^
  1669. sldkjf
  1670. ^^^^^^
  1671. lkjsfd
  1672. """
  1673. if not self.streamlined:
  1674. self.streamline()
  1675. for e in self.ignoreExprs:
  1676. e.streamline()
  1677. if not self.keepTabs:
  1678. instring = _ustr(instring).expandtabs()
  1679. instrlen = len(instring)
  1680. loc = 0
  1681. preparseFn = self.preParse
  1682. parseFn = self._parse
  1683. ParserElement.resetCache()
  1684. matches = 0
  1685. try:
  1686. while loc <= instrlen and matches < maxMatches:
  1687. try:
  1688. preloc = preparseFn(instring, loc)
  1689. nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)
  1690. except ParseException:
  1691. loc = preloc + 1
  1692. else:
  1693. if nextLoc > loc:
  1694. matches += 1
  1695. yield tokens, preloc, nextLoc
  1696. if overlap:
  1697. nextloc = preparseFn(instring, loc)
  1698. if nextloc > loc:
  1699. loc = nextLoc
  1700. else:
  1701. loc += 1
  1702. else:
  1703. loc = nextLoc
  1704. else:
  1705. loc = preloc + 1
  1706. except ParseBaseException as exc:
  1707. if ParserElement.verbose_stacktrace:
  1708. raise
  1709. else:
  1710. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  1711. if getattr(exc, '__traceback__', None) is not None:
  1712. exc.__traceback__ = self._trim_traceback(exc.__traceback__)
  1713. raise exc
  1714. def transformString(self, instring):
  1715. """
  1716. Extension to :class:`scanString`, to modify matching text with modified tokens that may
  1717. be returned from a parse action. To use ``transformString``, define a grammar and
  1718. attach a parse action to it that modifies the returned token list.
  1719. Invoking ``transformString()`` on a target string will then scan for matches,
  1720. and replace the matched text patterns according to the logic in the parse
  1721. action. ``transformString()`` returns the resulting transformed string.
  1722. Example::
  1723. wd = Word(alphas)
  1724. wd.setParseAction(lambda toks: toks[0].title())
  1725. print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
  1726. prints::
  1727. Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
  1728. """
  1729. out = []
  1730. lastE = 0
  1731. # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
  1732. # keep string locs straight between transformString and scanString
  1733. self.keepTabs = True
  1734. try:
  1735. for t, s, e in self.scanString(instring):
  1736. out.append(instring[lastE:s])
  1737. if t:
  1738. if isinstance(t, ParseResults):
  1739. out += t.asList()
  1740. elif isinstance(t, list):
  1741. out += t
  1742. else:
  1743. out.append(t)
  1744. lastE = e
  1745. out.append(instring[lastE:])
  1746. out = [o for o in out if o]
  1747. return "".join(map(_ustr, _flatten(out)))
  1748. except ParseBaseException as exc:
  1749. if ParserElement.verbose_stacktrace:
  1750. raise
  1751. else:
  1752. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  1753. if getattr(exc, '__traceback__', None) is not None:
  1754. exc.__traceback__ = self._trim_traceback(exc.__traceback__)
  1755. raise exc
  1756. def searchString(self, instring, maxMatches=_MAX_INT):
  1757. """
  1758. Another extension to :class:`scanString`, simplifying the access to the tokens found
  1759. to match the given parse expression. May be called with optional
  1760. ``maxMatches`` argument, to clip searching after 'n' matches are found.
  1761. Example::
  1762. # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
  1763. cap_word = Word(alphas.upper(), alphas.lower())
  1764. print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
  1765. # the sum() builtin can be used to merge results into a single ParseResults object
  1766. print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")))
  1767. prints::
  1768. [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
  1769. ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']
  1770. """
  1771. try:
  1772. return ParseResults([t for t, s, e in self.scanString(instring, maxMatches)])
  1773. except ParseBaseException as exc:
  1774. if ParserElement.verbose_stacktrace:
  1775. raise
  1776. else:
  1777. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  1778. if getattr(exc, '__traceback__', None) is not None:
  1779. exc.__traceback__ = self._trim_traceback(exc.__traceback__)
  1780. raise exc
  1781. def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
  1782. """
  1783. Generator method to split a string using the given expression as a separator.
  1784. May be called with optional ``maxsplit`` argument, to limit the number of splits;
  1785. and the optional ``includeSeparators`` argument (default= ``False``), if the separating
  1786. matching text should be included in the split results.
  1787. Example::
  1788. punc = oneOf(list(".,;:/-!?"))
  1789. print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
  1790. prints::
  1791. ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
  1792. """
  1793. splits = 0
  1794. last = 0
  1795. for t, s, e in self.scanString(instring, maxMatches=maxsplit):
  1796. yield instring[last:s]
  1797. if includeSeparators:
  1798. yield t[0]
  1799. last = e
  1800. yield instring[last:]
  1801. def __add__(self, other):
  1802. """
  1803. Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
  1804. converts them to :class:`Literal`s by default.
  1805. Example::
  1806. greet = Word(alphas) + "," + Word(alphas) + "!"
  1807. hello = "Hello, World!"
  1808. print (hello, "->", greet.parseString(hello))
  1809. prints::
  1810. Hello, World! -> ['Hello', ',', 'World', '!']
  1811. ``...`` may be used as a parse expression as a short form of :class:`SkipTo`.
  1812. Literal('start') + ... + Literal('end')
  1813. is equivalent to:
  1814. Literal('start') + SkipTo('end')("_skipped*") + Literal('end')
  1815. Note that the skipped text is returned with '_skipped' as a results name,
  1816. and to support having multiple skips in the same parser, the value returned is
  1817. a list of all skipped text.
  1818. """
  1819. if other is Ellipsis:
  1820. return _PendingSkip(self)
  1821. if isinstance(other, basestring):
  1822. other = self._literalStringClass(other)
  1823. if not isinstance(other, ParserElement):
  1824. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1825. SyntaxWarning, stacklevel=2)
  1826. return None
  1827. return And([self, other])
  1828. def __radd__(self, other):
  1829. """
  1830. Implementation of + operator when left operand is not a :class:`ParserElement`
  1831. """
  1832. if other is Ellipsis:
  1833. return SkipTo(self)("_skipped*") + self
  1834. if isinstance(other, basestring):
  1835. other = self._literalStringClass(other)
  1836. if not isinstance(other, ParserElement):
  1837. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1838. SyntaxWarning, stacklevel=2)
  1839. return None
  1840. return other + self
  1841. def __sub__(self, other):
  1842. """
  1843. Implementation of - operator, returns :class:`And` with error stop
  1844. """
  1845. if isinstance(other, basestring):
  1846. other = self._literalStringClass(other)
  1847. if not isinstance(other, ParserElement):
  1848. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1849. SyntaxWarning, stacklevel=2)
  1850. return None
  1851. return self + And._ErrorStop() + other
  1852. def __rsub__(self, other):
  1853. """
  1854. Implementation of - operator when left operand is not a :class:`ParserElement`
  1855. """
  1856. if isinstance(other, basestring):
  1857. other = self._literalStringClass(other)
  1858. if not isinstance(other, ParserElement):
  1859. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1860. SyntaxWarning, stacklevel=2)
  1861. return None
  1862. return other - self
  1863. def __mul__(self, other):
  1864. """
  1865. Implementation of * operator, allows use of ``expr * 3`` in place of
  1866. ``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
  1867. tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
  1868. may also include ``None`` as in:
  1869. - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
  1870. to ``expr*n + ZeroOrMore(expr)``
  1871. (read as "at least n instances of ``expr``")
  1872. - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
  1873. (read as "0 to n instances of ``expr``")
  1874. - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
  1875. - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
  1876. Note that ``expr*(None, n)`` does not raise an exception if
  1877. more than n exprs exist in the input stream; that is,
  1878. ``expr*(None, n)`` does not enforce a maximum number of expr
  1879. occurrences. If this behavior is desired, then write
  1880. ``expr*(None, n) + ~expr``
  1881. """
  1882. if other is Ellipsis:
  1883. other = (0, None)
  1884. elif isinstance(other, tuple) and other[:1] == (Ellipsis,):
  1885. other = ((0, ) + other[1:] + (None,))[:2]
  1886. if isinstance(other, int):
  1887. minElements, optElements = other, 0
  1888. elif isinstance(other, tuple):
  1889. other = tuple(o if o is not Ellipsis else None for o in other)
  1890. other = (other + (None, None))[:2]
  1891. if other[0] is None:
  1892. other = (0, other[1])
  1893. if isinstance(other[0], int) and other[1] is None:
  1894. if other[0] == 0:
  1895. return ZeroOrMore(self)
  1896. if other[0] == 1:
  1897. return OneOrMore(self)
  1898. else:
  1899. return self * other[0] + ZeroOrMore(self)
  1900. elif isinstance(other[0], int) and isinstance(other[1], int):
  1901. minElements, optElements = other
  1902. optElements -= minElements
  1903. else:
  1904. raise TypeError("cannot multiply 'ParserElement' and ('%s', '%s') objects", type(other[0]), type(other[1]))
  1905. else:
  1906. raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
  1907. if minElements < 0:
  1908. raise ValueError("cannot multiply ParserElement by negative value")
  1909. if optElements < 0:
  1910. raise ValueError("second tuple value must be greater or equal to first tuple value")
  1911. if minElements == optElements == 0:
  1912. raise ValueError("cannot multiply ParserElement by 0 or (0, 0)")
  1913. if optElements:
  1914. def makeOptionalList(n):
  1915. if n > 1:
  1916. return Optional(self + makeOptionalList(n - 1))
  1917. else:
  1918. return Optional(self)
  1919. if minElements:
  1920. if minElements == 1:
  1921. ret = self + makeOptionalList(optElements)
  1922. else:
  1923. ret = And([self] * minElements) + makeOptionalList(optElements)
  1924. else:
  1925. ret = makeOptionalList(optElements)
  1926. else:
  1927. if minElements == 1:
  1928. ret = self
  1929. else:
  1930. ret = And([self] * minElements)
  1931. return ret
  1932. def __rmul__(self, other):
  1933. return self.__mul__(other)
  1934. def __or__(self, other):
  1935. """
  1936. Implementation of | operator - returns :class:`MatchFirst`
  1937. """
  1938. if other is Ellipsis:
  1939. return _PendingSkip(self, must_skip=True)
  1940. if isinstance(other, basestring):
  1941. other = self._literalStringClass(other)
  1942. if not isinstance(other, ParserElement):
  1943. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1944. SyntaxWarning, stacklevel=2)
  1945. return None
  1946. return MatchFirst([self, other])
  1947. def __ror__(self, other):
  1948. """
  1949. Implementation of | operator when left operand is not a :class:`ParserElement`
  1950. """
  1951. if isinstance(other, basestring):
  1952. other = self._literalStringClass(other)
  1953. if not isinstance(other, ParserElement):
  1954. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1955. SyntaxWarning, stacklevel=2)
  1956. return None
  1957. return other | self
  1958. def __xor__(self, other):
  1959. """
  1960. Implementation of ^ operator - returns :class:`Or`
  1961. """
  1962. if isinstance(other, basestring):
  1963. other = self._literalStringClass(other)
  1964. if not isinstance(other, ParserElement):
  1965. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1966. SyntaxWarning, stacklevel=2)
  1967. return None
  1968. return Or([self, other])
  1969. def __rxor__(self, other):
  1970. """
  1971. Implementation of ^ operator when left operand is not a :class:`ParserElement`
  1972. """
  1973. if isinstance(other, basestring):
  1974. other = self._literalStringClass(other)
  1975. if not isinstance(other, ParserElement):
  1976. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1977. SyntaxWarning, stacklevel=2)
  1978. return None
  1979. return other ^ self
  1980. def __and__(self, other):
  1981. """
  1982. Implementation of & operator - returns :class:`Each`
  1983. """
  1984. if isinstance(other, basestring):
  1985. other = self._literalStringClass(other)
  1986. if not isinstance(other, ParserElement):
  1987. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1988. SyntaxWarning, stacklevel=2)
  1989. return None
  1990. return Each([self, other])
  1991. def __rand__(self, other):
  1992. """
  1993. Implementation of & operator when left operand is not a :class:`ParserElement`
  1994. """
  1995. if isinstance(other, basestring):
  1996. other = self._literalStringClass(other)
  1997. if not isinstance(other, ParserElement):
  1998. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1999. SyntaxWarning, stacklevel=2)
  2000. return None
  2001. return other & self
  2002. def __invert__(self):
  2003. """
  2004. Implementation of ~ operator - returns :class:`NotAny`
  2005. """
  2006. return NotAny(self)
  2007. def __iter__(self):
  2008. # must implement __iter__ to override legacy use of sequential access to __getitem__ to
  2009. # iterate over a sequence
  2010. raise TypeError('%r object is not iterable' % self.__class__.__name__)
  2011. def __getitem__(self, key):
  2012. """
  2013. use ``[]`` indexing notation as a short form for expression repetition:
  2014. - ``expr[n]`` is equivalent to ``expr*n``
  2015. - ``expr[m, n]`` is equivalent to ``expr*(m, n)``
  2016. - ``expr[n, ...]`` or ``expr[n,]`` is equivalent
  2017. to ``expr*n + ZeroOrMore(expr)``
  2018. (read as "at least n instances of ``expr``")
  2019. - ``expr[..., n]`` is equivalent to ``expr*(0, n)``
  2020. (read as "0 to n instances of ``expr``")
  2021. - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
  2022. - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
  2023. ``None`` may be used in place of ``...``.
  2024. Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception
  2025. if more than ``n`` ``expr``s exist in the input stream. If this behavior is
  2026. desired, then write ``expr[..., n] + ~expr``.
  2027. """
  2028. # convert single arg keys to tuples
  2029. try:
  2030. if isinstance(key, str):
  2031. key = (key,)
  2032. iter(key)
  2033. except TypeError:
  2034. key = (key, key)
  2035. if len(key) > 2:
  2036. warnings.warn("only 1 or 2 index arguments supported ({0}{1})".format(key[:5],
  2037. '... [{0}]'.format(len(key))
  2038. if len(key) > 5 else ''))
  2039. # clip to 2 elements
  2040. ret = self * tuple(key[:2])
  2041. return ret
  2042. def __call__(self, name=None):
  2043. """
  2044. Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.
  2045. If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be
  2046. passed as ``True``.
  2047. If ``name` is omitted, same as calling :class:`copy`.
  2048. Example::
  2049. # these are equivalent
  2050. userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno")
  2051. userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
  2052. """
  2053. if name is not None:
  2054. return self._setResultsName(name)
  2055. else:
  2056. return self.copy()
  2057. def suppress(self):
  2058. """
  2059. Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
  2060. cluttering up returned output.
  2061. """
  2062. return Suppress(self)
  2063. def leaveWhitespace(self):
  2064. """
  2065. Disables the skipping of whitespace before matching the characters in the
  2066. :class:`ParserElement`'s defined pattern. This is normally only used internally by
  2067. the pyparsing module, but may be needed in some whitespace-sensitive grammars.
  2068. """
  2069. self.skipWhitespace = False
  2070. return self
  2071. def setWhitespaceChars(self, chars):
  2072. """
  2073. Overrides the default whitespace chars
  2074. """
  2075. self.skipWhitespace = True
  2076. self.whiteChars = chars
  2077. self.copyDefaultWhiteChars = False
  2078. return self
  2079. def parseWithTabs(self):
  2080. """
  2081. Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
  2082. Must be called before ``parseString`` when the input grammar contains elements that
  2083. match ``<TAB>`` characters.
  2084. """
  2085. self.keepTabs = True
  2086. return self
  2087. def ignore(self, other):
  2088. """
  2089. Define expression to be ignored (e.g., comments) while doing pattern
  2090. matching; may be called repeatedly, to define multiple comment or other
  2091. ignorable patterns.
  2092. Example::
  2093. patt = OneOrMore(Word(alphas))
  2094. patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
  2095. patt.ignore(cStyleComment)
  2096. patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
  2097. """
  2098. if isinstance(other, basestring):
  2099. other = Suppress(other)
  2100. if isinstance(other, Suppress):
  2101. if other not in self.ignoreExprs:
  2102. self.ignoreExprs.append(other)
  2103. else:
  2104. self.ignoreExprs.append(Suppress(other.copy()))
  2105. return self
  2106. def setDebugActions(self, startAction, successAction, exceptionAction):
  2107. """
  2108. Enable display of debugging messages while doing pattern matching.
  2109. """
  2110. self.debugActions = (startAction or _defaultStartDebugAction,
  2111. successAction or _defaultSuccessDebugAction,
  2112. exceptionAction or _defaultExceptionDebugAction)
  2113. self.debug = True
  2114. return self
  2115. def setDebug(self, flag=True):
  2116. """
  2117. Enable display of debugging messages while doing pattern matching.
  2118. Set ``flag`` to True to enable, False to disable.
  2119. Example::
  2120. wd = Word(alphas).setName("alphaword")
  2121. integer = Word(nums).setName("numword")
  2122. term = wd | integer
  2123. # turn on debugging for wd
  2124. wd.setDebug()
  2125. OneOrMore(term).parseString("abc 123 xyz 890")
  2126. prints::
  2127. Match alphaword at loc 0(1,1)
  2128. Matched alphaword -> ['abc']
  2129. Match alphaword at loc 3(1,4)
  2130. Exception raised:Expected alphaword (at char 4), (line:1, col:5)
  2131. Match alphaword at loc 7(1,8)
  2132. Matched alphaword -> ['xyz']
  2133. Match alphaword at loc 11(1,12)
  2134. Exception raised:Expected alphaword (at char 12), (line:1, col:13)
  2135. Match alphaword at loc 15(1,16)
  2136. Exception raised:Expected alphaword (at char 15), (line:1, col:16)
  2137. The output shown is that produced by the default debug actions - custom debug actions can be
  2138. specified using :class:`setDebugActions`. Prior to attempting
  2139. to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"``
  2140. is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"``
  2141. message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression,
  2142. which makes debugging and exception messages easier to understand - for instance, the default
  2143. name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``.
  2144. """
  2145. if flag:
  2146. self.setDebugActions(_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction)
  2147. else:
  2148. self.debug = False
  2149. return self
  2150. def __str__(self):
  2151. return self.name
  2152. def __repr__(self):
  2153. return _ustr(self)
  2154. def streamline(self):
  2155. self.streamlined = True
  2156. self.strRepr = None
  2157. return self
  2158. def checkRecursion(self, parseElementList):
  2159. pass
  2160. def validate(self, validateTrace=None):
  2161. """
  2162. Check defined expressions for valid structure, check for infinite recursive definitions.
  2163. """
  2164. self.checkRecursion([])
  2165. def parseFile(self, file_or_filename, parseAll=False):
  2166. """
  2167. Execute the parse expression on the given file or filename.
  2168. If a filename is specified (instead of a file object),
  2169. the entire file is opened, read, and closed before parsing.
  2170. """
  2171. try:
  2172. file_contents = file_or_filename.read()
  2173. except AttributeError:
  2174. with open(file_or_filename, "r") as f:
  2175. file_contents = f.read()
  2176. try:
  2177. return self.parseString(file_contents, parseAll)
  2178. except ParseBaseException as exc:
  2179. if ParserElement.verbose_stacktrace:
  2180. raise
  2181. else:
  2182. # catch and re-raise exception from here, clearing out pyparsing internal stack trace
  2183. if getattr(exc, '__traceback__', None) is not None:
  2184. exc.__traceback__ = self._trim_traceback(exc.__traceback__)
  2185. raise exc
  2186. def __eq__(self, other):
  2187. if self is other:
  2188. return True
  2189. elif isinstance(other, basestring):
  2190. return self.matches(other)
  2191. elif isinstance(other, ParserElement):
  2192. return vars(self) == vars(other)
  2193. return False
  2194. def __ne__(self, other):
  2195. return not (self == other)
  2196. def __hash__(self):
  2197. return id(self)
  2198. def __req__(self, other):
  2199. return self == other
  2200. def __rne__(self, other):
  2201. return not (self == other)
  2202. def matches(self, testString, parseAll=True):
  2203. """
  2204. Method for quick testing of a parser against a test string. Good for simple
  2205. inline microtests of sub expressions while building up larger parser.
  2206. Parameters:
  2207. - testString - to test against this expression for a match
  2208. - parseAll - (default= ``True``) - flag to pass to :class:`parseString` when running tests
  2209. Example::
  2210. expr = Word(nums)
  2211. assert expr.matches("100")
  2212. """
  2213. try:
  2214. self.parseString(_ustr(testString), parseAll=parseAll)
  2215. return True
  2216. except ParseBaseException:
  2217. return False
  2218. def runTests(self, tests, parseAll=True, comment='#',
  2219. fullDump=True, printResults=True, failureTests=False, postParse=None,
  2220. file=None):
  2221. """
  2222. Execute the parse expression on a series of test strings, showing each
  2223. test, the parsed results or where the parse failed. Quick and easy way to
  2224. run a parse expression against a list of sample strings.
  2225. Parameters:
  2226. - tests - a list of separate test strings, or a multiline string of test strings
  2227. - parseAll - (default= ``True``) - flag to pass to :class:`parseString` when running tests
  2228. - comment - (default= ``'#'``) - expression for indicating embedded comments in the test
  2229. string; pass None to disable comment filtering
  2230. - fullDump - (default= ``True``) - dump results as list followed by results names in nested outline;
  2231. if False, only dump nested list
  2232. - printResults - (default= ``True``) prints test output to stdout
  2233. - failureTests - (default= ``False``) indicates if these tests are expected to fail parsing
  2234. - postParse - (default= ``None``) optional callback for successful parse results; called as
  2235. `fn(test_string, parse_results)` and returns a string to be added to the test output
  2236. - file - (default=``None``) optional file-like object to which test output will be written;
  2237. if None, will default to ``sys.stdout``
  2238. Returns: a (success, results) tuple, where success indicates that all tests succeeded
  2239. (or failed if ``failureTests`` is True), and the results contain a list of lines of each
  2240. test's output
  2241. Example::
  2242. number_expr = pyparsing_common.number.copy()
  2243. result = number_expr.runTests('''
  2244. # unsigned integer
  2245. 100
  2246. # negative integer
  2247. -100
  2248. # float with scientific notation
  2249. 6.02e23
  2250. # integer with scientific notation
  2251. 1e-12
  2252. ''')
  2253. print("Success" if result[0] else "Failed!")
  2254. result = number_expr.runTests('''
  2255. # stray character
  2256. 100Z
  2257. # missing leading digit before '.'
  2258. -.100
  2259. # too many '.'
  2260. 3.14.159
  2261. ''', failureTests=True)
  2262. print("Success" if result[0] else "Failed!")
  2263. prints::
  2264. # unsigned integer
  2265. 100
  2266. [100]
  2267. # negative integer
  2268. -100
  2269. [-100]
  2270. # float with scientific notation
  2271. 6.02e23
  2272. [6.02e+23]
  2273. # integer with scientific notation
  2274. 1e-12
  2275. [1e-12]
  2276. Success
  2277. # stray character
  2278. 100Z
  2279. ^
  2280. FAIL: Expected end of text (at char 3), (line:1, col:4)
  2281. # missing leading digit before '.'
  2282. -.100
  2283. ^
  2284. FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
  2285. # too many '.'
  2286. 3.14.159
  2287. ^
  2288. FAIL: Expected end of text (at char 4), (line:1, col:5)
  2289. Success
  2290. Each test string must be on a single line. If you want to test a string that spans multiple
  2291. lines, create a test like this::
  2292. expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
  2293. (Note that this is a raw string literal, you must include the leading 'r'.)
  2294. """
  2295. if isinstance(tests, basestring):
  2296. tests = list(map(str.strip, tests.rstrip().splitlines()))
  2297. if isinstance(comment, basestring):
  2298. comment = Literal(comment)
  2299. if file is None:
  2300. file = sys.stdout
  2301. print_ = file.write
  2302. allResults = []
  2303. comments = []
  2304. success = True
  2305. NL = Literal(r'\n').addParseAction(replaceWith('\n')).ignore(quotedString)
  2306. BOM = u'\ufeff'
  2307. for t in tests:
  2308. if comment is not None and comment.matches(t, False) or comments and not t:
  2309. comments.append(t)
  2310. continue
  2311. if not t:
  2312. continue
  2313. out = ['\n' + '\n'.join(comments) if comments else '', t]
  2314. comments = []
  2315. try:
  2316. # convert newline marks to actual newlines, and strip leading BOM if present
  2317. t = NL.transformString(t.lstrip(BOM))
  2318. result = self.parseString(t, parseAll=parseAll)
  2319. except ParseBaseException as pe:
  2320. fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
  2321. if '\n' in t:
  2322. out.append(line(pe.loc, t))
  2323. out.append(' ' * (col(pe.loc, t) - 1) + '^' + fatal)
  2324. else:
  2325. out.append(' ' * pe.loc + '^' + fatal)
  2326. out.append("FAIL: " + str(pe))
  2327. success = success and failureTests
  2328. result = pe
  2329. except Exception as exc:
  2330. out.append("FAIL-EXCEPTION: " + str(exc))
  2331. success = success and failureTests
  2332. result = exc
  2333. else:
  2334. success = success and not failureTests
  2335. if postParse is not None:
  2336. try:
  2337. pp_value = postParse(t, result)
  2338. if pp_value is not None:
  2339. if isinstance(pp_value, ParseResults):
  2340. out.append(pp_value.dump())
  2341. else:
  2342. out.append(str(pp_value))
  2343. else:
  2344. out.append(result.dump())
  2345. except Exception as e:
  2346. out.append(result.dump(full=fullDump))
  2347. out.append("{0} failed: {1}: {2}".format(postParse.__name__, type(e).__name__, e))
  2348. else:
  2349. out.append(result.dump(full=fullDump))
  2350. if printResults:
  2351. if fullDump:
  2352. out.append('')
  2353. print_('\n'.join(out))
  2354. allResults.append((t, result))
  2355. return success, allResults
  2356. class _PendingSkip(ParserElement):
  2357. # internal placeholder class to hold a place were '...' is added to a parser element,
  2358. # once another ParserElement is added, this placeholder will be replaced with a SkipTo
  2359. def __init__(self, expr, must_skip=False):
  2360. super(_PendingSkip, self).__init__()
  2361. self.strRepr = str(expr + Empty()).replace('Empty', '...')
  2362. self.name = self.strRepr
  2363. self.anchor = expr
  2364. self.must_skip = must_skip
  2365. def __add__(self, other):
  2366. skipper = SkipTo(other).setName("...")("_skipped*")
  2367. if self.must_skip:
  2368. def must_skip(t):
  2369. if not t._skipped or t._skipped.asList() == ['']:
  2370. del t[0]
  2371. t.pop("_skipped", None)
  2372. def show_skip(t):
  2373. if t._skipped.asList()[-1:] == ['']:
  2374. skipped = t.pop('_skipped')
  2375. t['_skipped'] = 'missing <' + repr(self.anchor) + '>'
  2376. return (self.anchor + skipper().addParseAction(must_skip)
  2377. | skipper().addParseAction(show_skip)) + other
  2378. return self.anchor + skipper + other
  2379. def __repr__(self):
  2380. return self.strRepr
  2381. def parseImpl(self, *args):
  2382. raise Exception("use of `...` expression without following SkipTo target expression")
  2383. class Token(ParserElement):
  2384. """Abstract :class:`ParserElement` subclass, for defining atomic
  2385. matching patterns.
  2386. """
  2387. def __init__(self):
  2388. super(Token, self).__init__(savelist=False)
  2389. class Empty(Token):
  2390. """An empty token, will always match.
  2391. """
  2392. def __init__(self):
  2393. super(Empty, self).__init__()
  2394. self.name = "Empty"
  2395. self.mayReturnEmpty = True
  2396. self.mayIndexError = False
  2397. class NoMatch(Token):
  2398. """A token that will never match.
  2399. """
  2400. def __init__(self):
  2401. super(NoMatch, self).__init__()
  2402. self.name = "NoMatch"
  2403. self.mayReturnEmpty = True
  2404. self.mayIndexError = False
  2405. self.errmsg = "Unmatchable token"
  2406. def parseImpl(self, instring, loc, doActions=True):
  2407. raise ParseException(instring, loc, self.errmsg, self)
  2408. class Literal(Token):
  2409. """Token to exactly match a specified string.
  2410. Example::
  2411. Literal('blah').parseString('blah') # -> ['blah']
  2412. Literal('blah').parseString('blahfooblah') # -> ['blah']
  2413. Literal('blah').parseString('bla') # -> Exception: Expected "blah"
  2414. For case-insensitive matching, use :class:`CaselessLiteral`.
  2415. For keyword matching (force word break before and after the matched string),
  2416. use :class:`Keyword` or :class:`CaselessKeyword`.
  2417. """
  2418. def __init__(self, matchString):
  2419. super(Literal, self).__init__()
  2420. self.match = matchString
  2421. self.matchLen = len(matchString)
  2422. try:
  2423. self.firstMatchChar = matchString[0]
  2424. except IndexError:
  2425. warnings.warn("null string passed to Literal; use Empty() instead",
  2426. SyntaxWarning, stacklevel=2)
  2427. self.__class__ = Empty
  2428. self.name = '"%s"' % _ustr(self.match)
  2429. self.errmsg = "Expected " + self.name
  2430. self.mayReturnEmpty = False
  2431. self.mayIndexError = False
  2432. # Performance tuning: modify __class__ to select
  2433. # a parseImpl optimized for single-character check
  2434. if self.matchLen == 1 and type(self) is Literal:
  2435. self.__class__ = _SingleCharLiteral
  2436. def parseImpl(self, instring, loc, doActions=True):
  2437. if instring[loc] == self.firstMatchChar and instring.startswith(self.match, loc):
  2438. return loc + self.matchLen, self.match
  2439. raise ParseException(instring, loc, self.errmsg, self)
  2440. class _SingleCharLiteral(Literal):
  2441. def parseImpl(self, instring, loc, doActions=True):
  2442. if instring[loc] == self.firstMatchChar:
  2443. return loc + 1, self.match
  2444. raise ParseException(instring, loc, self.errmsg, self)
  2445. _L = Literal
  2446. ParserElement._literalStringClass = Literal
  2447. class Keyword(Token):
  2448. """Token to exactly match a specified string as a keyword, that is,
  2449. it must be immediately followed by a non-keyword character. Compare
  2450. with :class:`Literal`:
  2451. - ``Literal("if")`` will match the leading ``'if'`` in
  2452. ``'ifAndOnlyIf'``.
  2453. - ``Keyword("if")`` will not; it will only match the leading
  2454. ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``
  2455. Accepts two optional constructor arguments in addition to the
  2456. keyword string:
  2457. - ``identChars`` is a string of characters that would be valid
  2458. identifier characters, defaulting to all alphanumerics + "_" and
  2459. "$"
  2460. - ``caseless`` allows case-insensitive matching, default is ``False``.
  2461. Example::
  2462. Keyword("start").parseString("start") # -> ['start']
  2463. Keyword("start").parseString("starting") # -> Exception
  2464. For case-insensitive matching, use :class:`CaselessKeyword`.
  2465. """
  2466. DEFAULT_KEYWORD_CHARS = alphanums + "_$"
  2467. def __init__(self, matchString, identChars=None, caseless=False):
  2468. super(Keyword, self).__init__()
  2469. if identChars is None:
  2470. identChars = Keyword.DEFAULT_KEYWORD_CHARS
  2471. self.match = matchString
  2472. self.matchLen = len(matchString)
  2473. try:
  2474. self.firstMatchChar = matchString[0]
  2475. except IndexError:
  2476. warnings.warn("null string passed to Keyword; use Empty() instead",
  2477. SyntaxWarning, stacklevel=2)
  2478. self.name = '"%s"' % self.match
  2479. self.errmsg = "Expected " + self.name
  2480. self.mayReturnEmpty = False
  2481. self.mayIndexError = False
  2482. self.caseless = caseless
  2483. if caseless:
  2484. self.caselessmatch = matchString.upper()
  2485. identChars = identChars.upper()
  2486. self.identChars = set(identChars)
  2487. def parseImpl(self, instring, loc, doActions=True):
  2488. if self.caseless:
  2489. if ((instring[loc:loc + self.matchLen].upper() == self.caselessmatch)
  2490. and (loc >= len(instring) - self.matchLen
  2491. or instring[loc + self.matchLen].upper() not in self.identChars)
  2492. and (loc == 0
  2493. or instring[loc - 1].upper() not in self.identChars)):
  2494. return loc + self.matchLen, self.match
  2495. else:
  2496. if instring[loc] == self.firstMatchChar:
  2497. if ((self.matchLen == 1 or instring.startswith(self.match, loc))
  2498. and (loc >= len(instring) - self.matchLen
  2499. or instring[loc + self.matchLen] not in self.identChars)
  2500. and (loc == 0 or instring[loc - 1] not in self.identChars)):
  2501. return loc + self.matchLen, self.match
  2502. raise ParseException(instring, loc, self.errmsg, self)
  2503. def copy(self):
  2504. c = super(Keyword, self).copy()
  2505. c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
  2506. return c
  2507. @staticmethod
  2508. def setDefaultKeywordChars(chars):
  2509. """Overrides the default Keyword chars
  2510. """
  2511. Keyword.DEFAULT_KEYWORD_CHARS = chars
  2512. class CaselessLiteral(Literal):
  2513. """Token to match a specified string, ignoring case of letters.
  2514. Note: the matched results will always be in the case of the given
  2515. match string, NOT the case of the input text.
  2516. Example::
  2517. OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD']
  2518. (Contrast with example for :class:`CaselessKeyword`.)
  2519. """
  2520. def __init__(self, matchString):
  2521. super(CaselessLiteral, self).__init__(matchString.upper())
  2522. # Preserve the defining literal.
  2523. self.returnString = matchString
  2524. self.name = "'%s'" % self.returnString
  2525. self.errmsg = "Expected " + self.name
  2526. def parseImpl(self, instring, loc, doActions=True):
  2527. if instring[loc:loc + self.matchLen].upper() == self.match:
  2528. return loc + self.matchLen, self.returnString
  2529. raise ParseException(instring, loc, self.errmsg, self)
  2530. class CaselessKeyword(Keyword):
  2531. """
  2532. Caseless version of :class:`Keyword`.
  2533. Example::
  2534. OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD']
  2535. (Contrast with example for :class:`CaselessLiteral`.)
  2536. """
  2537. def __init__(self, matchString, identChars=None):
  2538. super(CaselessKeyword, self).__init__(matchString, identChars, caseless=True)
  2539. class CloseMatch(Token):
  2540. """A variation on :class:`Literal` which matches "close" matches,
  2541. that is, strings with at most 'n' mismatching characters.
  2542. :class:`CloseMatch` takes parameters:
  2543. - ``match_string`` - string to be matched
  2544. - ``maxMismatches`` - (``default=1``) maximum number of
  2545. mismatches allowed to count as a match
  2546. The results from a successful parse will contain the matched text
  2547. from the input string and the following named results:
  2548. - ``mismatches`` - a list of the positions within the
  2549. match_string where mismatches were found
  2550. - ``original`` - the original match_string used to compare
  2551. against the input string
  2552. If ``mismatches`` is an empty list, then the match was an exact
  2553. match.
  2554. Example::
  2555. patt = CloseMatch("ATCATCGAATGGA")
  2556. patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
  2557. patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)
  2558. # exact match
  2559. patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})
  2560. # close match allowing up to 2 mismatches
  2561. patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2)
  2562. patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
  2563. """
  2564. def __init__(self, match_string, maxMismatches=1):
  2565. super(CloseMatch, self).__init__()
  2566. self.name = match_string
  2567. self.match_string = match_string
  2568. self.maxMismatches = maxMismatches
  2569. self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches)
  2570. self.mayIndexError = False
  2571. self.mayReturnEmpty = False
  2572. def parseImpl(self, instring, loc, doActions=True):
  2573. start = loc
  2574. instrlen = len(instring)
  2575. maxloc = start + len(self.match_string)
  2576. if maxloc <= instrlen:
  2577. match_string = self.match_string
  2578. match_stringloc = 0
  2579. mismatches = []
  2580. maxMismatches = self.maxMismatches
  2581. for match_stringloc, s_m in enumerate(zip(instring[loc:maxloc], match_string)):
  2582. src, mat = s_m
  2583. if src != mat:
  2584. mismatches.append(match_stringloc)
  2585. if len(mismatches) > maxMismatches:
  2586. break
  2587. else:
  2588. loc = match_stringloc + 1
  2589. results = ParseResults([instring[start:loc]])
  2590. results['original'] = match_string
  2591. results['mismatches'] = mismatches
  2592. return loc, results
  2593. raise ParseException(instring, loc, self.errmsg, self)
  2594. class Word(Token):
  2595. """Token for matching words composed of allowed character sets.
  2596. Defined with string containing all allowed initial characters, an
  2597. optional string containing allowed body characters (if omitted,
  2598. defaults to the initial character set), and an optional minimum,
  2599. maximum, and/or exact length. The default value for ``min`` is
  2600. 1 (a minimum value < 1 is not valid); the default values for
  2601. ``max`` and ``exact`` are 0, meaning no maximum or exact
  2602. length restriction. An optional ``excludeChars`` parameter can
  2603. list characters that might be found in the input ``bodyChars``
  2604. string; useful to define a word of all printables except for one or
  2605. two characters, for instance.
  2606. :class:`srange` is useful for defining custom character set strings
  2607. for defining ``Word`` expressions, using range notation from
  2608. regular expression character sets.
  2609. A common mistake is to use :class:`Word` to match a specific literal
  2610. string, as in ``Word("Address")``. Remember that :class:`Word`
  2611. uses the string argument to define *sets* of matchable characters.
  2612. This expression would match "Add", "AAA", "dAred", or any other word
  2613. made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an
  2614. exact literal string, use :class:`Literal` or :class:`Keyword`.
  2615. pyparsing includes helper strings for building Words:
  2616. - :class:`alphas`
  2617. - :class:`nums`
  2618. - :class:`alphanums`
  2619. - :class:`hexnums`
  2620. - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255
  2621. - accented, tilded, umlauted, etc.)
  2622. - :class:`punc8bit` (non-alphabetic characters in ASCII range
  2623. 128-255 - currency, symbols, superscripts, diacriticals, etc.)
  2624. - :class:`printables` (any non-whitespace character)
  2625. Example::
  2626. # a word composed of digits
  2627. integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
  2628. # a word with a leading capital, and zero or more lowercase
  2629. capital_word = Word(alphas.upper(), alphas.lower())
  2630. # hostnames are alphanumeric, with leading alpha, and '-'
  2631. hostname = Word(alphas, alphanums + '-')
  2632. # roman numeral (not a strict parser, accepts invalid mix of characters)
  2633. roman = Word("IVXLCDM")
  2634. # any string of non-whitespace characters, except for ','
  2635. csv_value = Word(printables, excludeChars=",")
  2636. """
  2637. def __init__(self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None):
  2638. super(Word, self).__init__()
  2639. if excludeChars:
  2640. excludeChars = set(excludeChars)
  2641. initChars = ''.join(c for c in initChars if c not in excludeChars)
  2642. if bodyChars:
  2643. bodyChars = ''.join(c for c in bodyChars if c not in excludeChars)
  2644. self.initCharsOrig = initChars
  2645. self.initChars = set(initChars)
  2646. if bodyChars:
  2647. self.bodyCharsOrig = bodyChars
  2648. self.bodyChars = set(bodyChars)
  2649. else:
  2650. self.bodyCharsOrig = initChars
  2651. self.bodyChars = set(initChars)
  2652. self.maxSpecified = max > 0
  2653. if min < 1:
  2654. raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
  2655. self.minLen = min
  2656. if max > 0:
  2657. self.maxLen = max
  2658. else:
  2659. self.maxLen = _MAX_INT
  2660. if exact > 0:
  2661. self.maxLen = exact
  2662. self.minLen = exact
  2663. self.name = _ustr(self)
  2664. self.errmsg = "Expected " + self.name
  2665. self.mayIndexError = False
  2666. self.asKeyword = asKeyword
  2667. if ' ' not in self.initCharsOrig + self.bodyCharsOrig and (min == 1 and max == 0 and exact == 0):
  2668. if self.bodyCharsOrig == self.initCharsOrig:
  2669. self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
  2670. elif len(self.initCharsOrig) == 1:
  2671. self.reString = "%s[%s]*" % (re.escape(self.initCharsOrig),
  2672. _escapeRegexRangeChars(self.bodyCharsOrig),)
  2673. else:
  2674. self.reString = "[%s][%s]*" % (_escapeRegexRangeChars(self.initCharsOrig),
  2675. _escapeRegexRangeChars(self.bodyCharsOrig),)
  2676. if self.asKeyword:
  2677. self.reString = r"\b" + self.reString + r"\b"
  2678. try:
  2679. self.re = re.compile(self.reString)
  2680. except Exception:
  2681. self.re = None
  2682. else:
  2683. self.re_match = self.re.match
  2684. self.__class__ = _WordRegex
  2685. def parseImpl(self, instring, loc, doActions=True):
  2686. if instring[loc] not in self.initChars:
  2687. raise ParseException(instring, loc, self.errmsg, self)
  2688. start = loc
  2689. loc += 1
  2690. instrlen = len(instring)
  2691. bodychars = self.bodyChars
  2692. maxloc = start + self.maxLen
  2693. maxloc = min(maxloc, instrlen)
  2694. while loc < maxloc and instring[loc] in bodychars:
  2695. loc += 1
  2696. throwException = False
  2697. if loc - start < self.minLen:
  2698. throwException = True
  2699. elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
  2700. throwException = True
  2701. elif self.asKeyword:
  2702. if (start > 0 and instring[start - 1] in bodychars
  2703. or loc < instrlen and instring[loc] in bodychars):
  2704. throwException = True
  2705. if throwException:
  2706. raise ParseException(instring, loc, self.errmsg, self)
  2707. return loc, instring[start:loc]
  2708. def __str__(self):
  2709. try:
  2710. return super(Word, self).__str__()
  2711. except Exception:
  2712. pass
  2713. if self.strRepr is None:
  2714. def charsAsStr(s):
  2715. if len(s) > 4:
  2716. return s[:4] + "..."
  2717. else:
  2718. return s
  2719. if self.initCharsOrig != self.bodyCharsOrig:
  2720. self.strRepr = "W:(%s, %s)" % (charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig))
  2721. else:
  2722. self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
  2723. return self.strRepr
  2724. class _WordRegex(Word):
  2725. def parseImpl(self, instring, loc, doActions=True):
  2726. result = self.re_match(instring, loc)
  2727. if not result:
  2728. raise ParseException(instring, loc, self.errmsg, self)
  2729. loc = result.end()
  2730. return loc, result.group()
  2731. class Char(_WordRegex):
  2732. """A short-cut class for defining ``Word(characters, exact=1)``,
  2733. when defining a match of any single character in a string of
  2734. characters.
  2735. """
  2736. def __init__(self, charset, asKeyword=False, excludeChars=None):
  2737. super(Char, self).__init__(charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars)
  2738. self.reString = "[%s]" % _escapeRegexRangeChars(''.join(self.initChars))
  2739. if asKeyword:
  2740. self.reString = r"\b%s\b" % self.reString
  2741. self.re = re.compile(self.reString)
  2742. self.re_match = self.re.match
  2743. class Regex(Token):
  2744. r"""Token for matching strings that match a given regular
  2745. expression. Defined with string specifying the regular expression in
  2746. a form recognized by the stdlib Python `re module <https://docs.python.org/3/library/re.html>`_.
  2747. If the given regex contains named groups (defined using ``(?P<name>...)``),
  2748. these will be preserved as named parse results.
  2749. If instead of the Python stdlib re module you wish to use a different RE module
  2750. (such as the `regex` module), you can replace it by either building your
  2751. Regex object with a compiled RE that was compiled using regex:
  2752. Example::
  2753. realnum = Regex(r"[+-]?\d+\.\d*")
  2754. date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
  2755. # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
  2756. roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
  2757. # use regex module instead of stdlib re module to construct a Regex using
  2758. # a compiled regular expression
  2759. import regex
  2760. parser = pp.Regex(regex.compile(r'[0-9]'))
  2761. """
  2762. def __init__(self, pattern, flags=0, asGroupList=False, asMatch=False):
  2763. """The parameters ``pattern`` and ``flags`` are passed
  2764. to the ``re.compile()`` function as-is. See the Python
  2765. `re module <https://docs.python.org/3/library/re.html>`_ module for an
  2766. explanation of the acceptable patterns and flags.
  2767. """
  2768. super(Regex, self).__init__()
  2769. if isinstance(pattern, basestring):
  2770. if not pattern:
  2771. warnings.warn("null string passed to Regex; use Empty() instead",
  2772. SyntaxWarning, stacklevel=2)
  2773. self.pattern = pattern
  2774. self.flags = flags
  2775. try:
  2776. self.re = re.compile(self.pattern, self.flags)
  2777. self.reString = self.pattern
  2778. except sre_constants.error:
  2779. warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
  2780. SyntaxWarning, stacklevel=2)
  2781. raise
  2782. elif hasattr(pattern, 'pattern') and hasattr(pattern, 'match'):
  2783. self.re = pattern
  2784. self.pattern = self.reString = pattern.pattern
  2785. self.flags = flags
  2786. else:
  2787. raise TypeError("Regex may only be constructed with a string or a compiled RE object")
  2788. self.re_match = self.re.match
  2789. self.name = _ustr(self)
  2790. self.errmsg = "Expected " + self.name
  2791. self.mayIndexError = False
  2792. self.mayReturnEmpty = self.re_match("") is not None
  2793. self.asGroupList = asGroupList
  2794. self.asMatch = asMatch
  2795. if self.asGroupList:
  2796. self.parseImpl = self.parseImplAsGroupList
  2797. if self.asMatch:
  2798. self.parseImpl = self.parseImplAsMatch
  2799. def parseImpl(self, instring, loc, doActions=True):
  2800. result = self.re_match(instring, loc)
  2801. if not result:
  2802. raise ParseException(instring, loc, self.errmsg, self)
  2803. loc = result.end()
  2804. ret = ParseResults(result.group())
  2805. d = result.groupdict()
  2806. if d:
  2807. for k, v in d.items():
  2808. ret[k] = v
  2809. return loc, ret
  2810. def parseImplAsGroupList(self, instring, loc, doActions=True):
  2811. result = self.re_match(instring, loc)
  2812. if not result:
  2813. raise ParseException(instring, loc, self.errmsg, self)
  2814. loc = result.end()
  2815. ret = result.groups()
  2816. return loc, ret
  2817. def parseImplAsMatch(self, instring, loc, doActions=True):
  2818. result = self.re_match(instring, loc)
  2819. if not result:
  2820. raise ParseException(instring, loc, self.errmsg, self)
  2821. loc = result.end()
  2822. ret = result
  2823. return loc, ret
  2824. def __str__(self):
  2825. try:
  2826. return super(Regex, self).__str__()
  2827. except Exception:
  2828. pass
  2829. if self.strRepr is None:
  2830. self.strRepr = "Re:(%s)" % repr(self.pattern)
  2831. return self.strRepr
  2832. def sub(self, repl):
  2833. r"""
  2834. Return Regex with an attached parse action to transform the parsed
  2835. result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
  2836. Example::
  2837. make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>")
  2838. print(make_html.transformString("h1:main title:"))
  2839. # prints "<h1>main title</h1>"
  2840. """
  2841. if self.asGroupList:
  2842. warnings.warn("cannot use sub() with Regex(asGroupList=True)",
  2843. SyntaxWarning, stacklevel=2)
  2844. raise SyntaxError()
  2845. if self.asMatch and callable(repl):
  2846. warnings.warn("cannot use sub() with a callable with Regex(asMatch=True)",
  2847. SyntaxWarning, stacklevel=2)
  2848. raise SyntaxError()
  2849. if self.asMatch:
  2850. def pa(tokens):
  2851. return tokens[0].expand(repl)
  2852. else:
  2853. def pa(tokens):
  2854. return self.re.sub(repl, tokens[0])
  2855. return self.addParseAction(pa)
  2856. class QuotedString(Token):
  2857. r"""
  2858. Token for matching strings that are delimited by quoting characters.
  2859. Defined with the following parameters:
  2860. - quoteChar - string of one or more characters defining the
  2861. quote delimiting string
  2862. - escChar - character to escape quotes, typically backslash
  2863. (default= ``None``)
  2864. - escQuote - special quote sequence to escape an embedded quote
  2865. string (such as SQL's ``""`` to escape an embedded ``"``)
  2866. (default= ``None``)
  2867. - multiline - boolean indicating whether quotes can span
  2868. multiple lines (default= ``False``)
  2869. - unquoteResults - boolean indicating whether the matched text
  2870. should be unquoted (default= ``True``)
  2871. - endQuoteChar - string of one or more characters defining the
  2872. end of the quote delimited string (default= ``None`` => same as
  2873. quoteChar)
  2874. - convertWhitespaceEscapes - convert escaped whitespace
  2875. (``'\t'``, ``'\n'``, etc.) to actual whitespace
  2876. (default= ``True``)
  2877. Example::
  2878. qs = QuotedString('"')
  2879. print(qs.searchString('lsjdf "This is the quote" sldjf'))
  2880. complex_qs = QuotedString('{{', endQuoteChar='}}')
  2881. print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf'))
  2882. sql_qs = QuotedString('"', escQuote='""')
  2883. print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
  2884. prints::
  2885. [['This is the quote']]
  2886. [['This is the "quote"']]
  2887. [['This is the quote with "embedded" quotes']]
  2888. """
  2889. def __init__(self, quoteChar, escChar=None, escQuote=None, multiline=False,
  2890. unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True):
  2891. super(QuotedString, self).__init__()
  2892. # remove white space from quote chars - wont work anyway
  2893. quoteChar = quoteChar.strip()
  2894. if not quoteChar:
  2895. warnings.warn("quoteChar cannot be the empty string", SyntaxWarning, stacklevel=2)
  2896. raise SyntaxError()
  2897. if endQuoteChar is None:
  2898. endQuoteChar = quoteChar
  2899. else:
  2900. endQuoteChar = endQuoteChar.strip()
  2901. if not endQuoteChar:
  2902. warnings.warn("endQuoteChar cannot be the empty string", SyntaxWarning, stacklevel=2)
  2903. raise SyntaxError()
  2904. self.quoteChar = quoteChar
  2905. self.quoteCharLen = len(quoteChar)
  2906. self.firstQuoteChar = quoteChar[0]
  2907. self.endQuoteChar = endQuoteChar
  2908. self.endQuoteCharLen = len(endQuoteChar)
  2909. self.escChar = escChar
  2910. self.escQuote = escQuote
  2911. self.unquoteResults = unquoteResults
  2912. self.convertWhitespaceEscapes = convertWhitespaceEscapes
  2913. if multiline:
  2914. self.flags = re.MULTILINE | re.DOTALL
  2915. self.pattern = r'%s(?:[^%s%s]' % (re.escape(self.quoteChar),
  2916. _escapeRegexRangeChars(self.endQuoteChar[0]),
  2917. (escChar is not None and _escapeRegexRangeChars(escChar) or ''))
  2918. else:
  2919. self.flags = 0
  2920. self.pattern = r'%s(?:[^%s\n\r%s]' % (re.escape(self.quoteChar),
  2921. _escapeRegexRangeChars(self.endQuoteChar[0]),
  2922. (escChar is not None and _escapeRegexRangeChars(escChar) or ''))
  2923. if len(self.endQuoteChar) > 1:
  2924. self.pattern += (
  2925. '|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
  2926. _escapeRegexRangeChars(self.endQuoteChar[i]))
  2927. for i in range(len(self.endQuoteChar) - 1, 0, -1)) + ')')
  2928. if escQuote:
  2929. self.pattern += (r'|(?:%s)' % re.escape(escQuote))
  2930. if escChar:
  2931. self.pattern += (r'|(?:%s.)' % re.escape(escChar))
  2932. self.escCharReplacePattern = re.escape(self.escChar) + "(.)"
  2933. self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
  2934. try:
  2935. self.re = re.compile(self.pattern, self.flags)
  2936. self.reString = self.pattern
  2937. self.re_match = self.re.match
  2938. except sre_constants.error:
  2939. warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
  2940. SyntaxWarning, stacklevel=2)
  2941. raise
  2942. self.name = _ustr(self)
  2943. self.errmsg = "Expected " + self.name
  2944. self.mayIndexError = False
  2945. self.mayReturnEmpty = True
  2946. def parseImpl(self, instring, loc, doActions=True):
  2947. result = instring[loc] == self.firstQuoteChar and self.re_match(instring, loc) or None
  2948. if not result:
  2949. raise ParseException(instring, loc, self.errmsg, self)
  2950. loc = result.end()
  2951. ret = result.group()
  2952. if self.unquoteResults:
  2953. # strip off quotes
  2954. ret = ret[self.quoteCharLen: -self.endQuoteCharLen]
  2955. if isinstance(ret, basestring):
  2956. # replace escaped whitespace
  2957. if '\\' in ret and self.convertWhitespaceEscapes:
  2958. ws_map = {
  2959. r'\t': '\t',
  2960. r'\n': '\n',
  2961. r'\f': '\f',
  2962. r'\r': '\r',
  2963. }
  2964. for wslit, wschar in ws_map.items():
  2965. ret = ret.replace(wslit, wschar)
  2966. # replace escaped characters
  2967. if self.escChar:
  2968. ret = re.sub(self.escCharReplacePattern, r"\g<1>", ret)
  2969. # replace escaped quotes
  2970. if self.escQuote:
  2971. ret = ret.replace(self.escQuote, self.endQuoteChar)
  2972. return loc, ret
  2973. def __str__(self):
  2974. try:
  2975. return super(QuotedString, self).__str__()
  2976. except Exception:
  2977. pass
  2978. if self.strRepr is None:
  2979. self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
  2980. return self.strRepr
  2981. class CharsNotIn(Token):
  2982. """Token for matching words composed of characters *not* in a given
  2983. set (will include whitespace in matched characters if not listed in
  2984. the provided exclusion set - see example). Defined with string
  2985. containing all disallowed characters, and an optional minimum,
  2986. maximum, and/or exact length. The default value for ``min`` is
  2987. 1 (a minimum value < 1 is not valid); the default values for
  2988. ``max`` and ``exact`` are 0, meaning no maximum or exact
  2989. length restriction.
  2990. Example::
  2991. # define a comma-separated-value as anything that is not a ','
  2992. csv_value = CharsNotIn(',')
  2993. print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213"))
  2994. prints::
  2995. ['dkls', 'lsdkjf', 's12 34', '@!#', '213']
  2996. """
  2997. def __init__(self, notChars, min=1, max=0, exact=0):
  2998. super(CharsNotIn, self).__init__()
  2999. self.skipWhitespace = False
  3000. self.notChars = notChars
  3001. if min < 1:
  3002. raise ValueError("cannot specify a minimum length < 1; use "
  3003. "Optional(CharsNotIn()) if zero-length char group is permitted")
  3004. self.minLen = min
  3005. if max > 0:
  3006. self.maxLen = max
  3007. else:
  3008. self.maxLen = _MAX_INT
  3009. if exact > 0:
  3010. self.maxLen = exact
  3011. self.minLen = exact
  3012. self.name = _ustr(self)
  3013. self.errmsg = "Expected " + self.name
  3014. self.mayReturnEmpty = (self.minLen == 0)
  3015. self.mayIndexError = False
  3016. def parseImpl(self, instring, loc, doActions=True):
  3017. if instring[loc] in self.notChars:
  3018. raise ParseException(instring, loc, self.errmsg, self)
  3019. start = loc
  3020. loc += 1
  3021. notchars = self.notChars
  3022. maxlen = min(start + self.maxLen, len(instring))
  3023. while loc < maxlen and instring[loc] not in notchars:
  3024. loc += 1
  3025. if loc - start < self.minLen:
  3026. raise ParseException(instring, loc, self.errmsg, self)
  3027. return loc, instring[start:loc]
  3028. def __str__(self):
  3029. try:
  3030. return super(CharsNotIn, self).__str__()
  3031. except Exception:
  3032. pass
  3033. if self.strRepr is None:
  3034. if len(self.notChars) > 4:
  3035. self.strRepr = "!W:(%s...)" % self.notChars[:4]
  3036. else:
  3037. self.strRepr = "!W:(%s)" % self.notChars
  3038. return self.strRepr
  3039. class White(Token):
  3040. """Special matching class for matching whitespace. Normally,
  3041. whitespace is ignored by pyparsing grammars. This class is included
  3042. when some whitespace structures are significant. Define with
  3043. a string containing the whitespace characters to be matched; default
  3044. is ``" \\t\\r\\n"``. Also takes optional ``min``,
  3045. ``max``, and ``exact`` arguments, as defined for the
  3046. :class:`Word` class.
  3047. """
  3048. whiteStrs = {
  3049. ' ' : '<SP>',
  3050. '\t': '<TAB>',
  3051. '\n': '<LF>',
  3052. '\r': '<CR>',
  3053. '\f': '<FF>',
  3054. u'\u00A0': '<NBSP>',
  3055. u'\u1680': '<OGHAM_SPACE_MARK>',
  3056. u'\u180E': '<MONGOLIAN_VOWEL_SEPARATOR>',
  3057. u'\u2000': '<EN_QUAD>',
  3058. u'\u2001': '<EM_QUAD>',
  3059. u'\u2002': '<EN_SPACE>',
  3060. u'\u2003': '<EM_SPACE>',
  3061. u'\u2004': '<THREE-PER-EM_SPACE>',
  3062. u'\u2005': '<FOUR-PER-EM_SPACE>',
  3063. u'\u2006': '<SIX-PER-EM_SPACE>',
  3064. u'\u2007': '<FIGURE_SPACE>',
  3065. u'\u2008': '<PUNCTUATION_SPACE>',
  3066. u'\u2009': '<THIN_SPACE>',
  3067. u'\u200A': '<HAIR_SPACE>',
  3068. u'\u200B': '<ZERO_WIDTH_SPACE>',
  3069. u'\u202F': '<NNBSP>',
  3070. u'\u205F': '<MMSP>',
  3071. u'\u3000': '<IDEOGRAPHIC_SPACE>',
  3072. }
  3073. def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
  3074. super(White, self).__init__()
  3075. self.matchWhite = ws
  3076. self.setWhitespaceChars("".join(c for c in self.whiteChars if c not in self.matchWhite))
  3077. # ~ self.leaveWhitespace()
  3078. self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite))
  3079. self.mayReturnEmpty = True
  3080. self.errmsg = "Expected " + self.name
  3081. self.minLen = min
  3082. if max > 0:
  3083. self.maxLen = max
  3084. else:
  3085. self.maxLen = _MAX_INT
  3086. if exact > 0:
  3087. self.maxLen = exact
  3088. self.minLen = exact
  3089. def parseImpl(self, instring, loc, doActions=True):
  3090. if instring[loc] not in self.matchWhite:
  3091. raise ParseException(instring, loc, self.errmsg, self)
  3092. start = loc
  3093. loc += 1
  3094. maxloc = start + self.maxLen
  3095. maxloc = min(maxloc, len(instring))
  3096. while loc < maxloc and instring[loc] in self.matchWhite:
  3097. loc += 1
  3098. if loc - start < self.minLen:
  3099. raise ParseException(instring, loc, self.errmsg, self)
  3100. return loc, instring[start:loc]
  3101. class _PositionToken(Token):
  3102. def __init__(self):
  3103. super(_PositionToken, self).__init__()
  3104. self.name = self.__class__.__name__
  3105. self.mayReturnEmpty = True
  3106. self.mayIndexError = False
  3107. class GoToColumn(_PositionToken):
  3108. """Token to advance to a specific column of input text; useful for
  3109. tabular report scraping.
  3110. """
  3111. def __init__(self, colno):
  3112. super(GoToColumn, self).__init__()
  3113. self.col = colno
  3114. def preParse(self, instring, loc):
  3115. if col(loc, instring) != self.col:
  3116. instrlen = len(instring)
  3117. if self.ignoreExprs:
  3118. loc = self._skipIgnorables(instring, loc)
  3119. while loc < instrlen and instring[loc].isspace() and col(loc, instring) != self.col:
  3120. loc += 1
  3121. return loc
  3122. def parseImpl(self, instring, loc, doActions=True):
  3123. thiscol = col(loc, instring)
  3124. if thiscol > self.col:
  3125. raise ParseException(instring, loc, "Text not in expected column", self)
  3126. newloc = loc + self.col - thiscol
  3127. ret = instring[loc: newloc]
  3128. return newloc, ret
  3129. class LineStart(_PositionToken):
  3130. r"""Matches if current position is at the beginning of a line within
  3131. the parse string
  3132. Example::
  3133. test = '''\
  3134. AAA this line
  3135. AAA and this line
  3136. AAA but not this one
  3137. B AAA and definitely not this one
  3138. '''
  3139. for t in (LineStart() + 'AAA' + restOfLine).searchString(test):
  3140. print(t)
  3141. prints::
  3142. ['AAA', ' this line']
  3143. ['AAA', ' and this line']
  3144. """
  3145. def __init__(self):
  3146. super(LineStart, self).__init__()
  3147. self.errmsg = "Expected start of line"
  3148. def parseImpl(self, instring, loc, doActions=True):
  3149. if col(loc, instring) == 1:
  3150. return loc, []
  3151. raise ParseException(instring, loc, self.errmsg, self)
  3152. class LineEnd(_PositionToken):
  3153. """Matches if current position is at the end of a line within the
  3154. parse string
  3155. """
  3156. def __init__(self):
  3157. super(LineEnd, self).__init__()
  3158. self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace("\n", ""))
  3159. self.errmsg = "Expected end of line"
  3160. def parseImpl(self, instring, loc, doActions=True):
  3161. if loc < len(instring):
  3162. if instring[loc] == "\n":
  3163. return loc + 1, "\n"
  3164. else:
  3165. raise ParseException(instring, loc, self.errmsg, self)
  3166. elif loc == len(instring):
  3167. return loc + 1, []
  3168. else:
  3169. raise ParseException(instring, loc, self.errmsg, self)
  3170. class StringStart(_PositionToken):
  3171. """Matches if current position is at the beginning of the parse
  3172. string
  3173. """
  3174. def __init__(self):
  3175. super(StringStart, self).__init__()
  3176. self.errmsg = "Expected start of text"
  3177. def parseImpl(self, instring, loc, doActions=True):
  3178. if loc != 0:
  3179. # see if entire string up to here is just whitespace and ignoreables
  3180. if loc != self.preParse(instring, 0):
  3181. raise ParseException(instring, loc, self.errmsg, self)
  3182. return loc, []
  3183. class StringEnd(_PositionToken):
  3184. """Matches if current position is at the end of the parse string
  3185. """
  3186. def __init__(self):
  3187. super(StringEnd, self).__init__()
  3188. self.errmsg = "Expected end of text"
  3189. def parseImpl(self, instring, loc, doActions=True):
  3190. if loc < len(instring):
  3191. raise ParseException(instring, loc, self.errmsg, self)
  3192. elif loc == len(instring):
  3193. return loc + 1, []
  3194. elif loc > len(instring):
  3195. return loc, []
  3196. else:
  3197. raise ParseException(instring, loc, self.errmsg, self)
  3198. class WordStart(_PositionToken):
  3199. """Matches if the current position is at the beginning of a Word,
  3200. and is not preceded by any character in a given set of
  3201. ``wordChars`` (default= ``printables``). To emulate the
  3202. ``\b`` behavior of regular expressions, use
  3203. ``WordStart(alphanums)``. ``WordStart`` will also match at
  3204. the beginning of the string being parsed, or at the beginning of
  3205. a line.
  3206. """
  3207. def __init__(self, wordChars=printables):
  3208. super(WordStart, self).__init__()
  3209. self.wordChars = set(wordChars)
  3210. self.errmsg = "Not at the start of a word"
  3211. def parseImpl(self, instring, loc, doActions=True):
  3212. if loc != 0:
  3213. if (instring[loc - 1] in self.wordChars
  3214. or instring[loc] not in self.wordChars):
  3215. raise ParseException(instring, loc, self.errmsg, self)
  3216. return loc, []
  3217. class WordEnd(_PositionToken):
  3218. """Matches if the current position is at the end of a Word, and is
  3219. not followed by any character in a given set of ``wordChars``
  3220. (default= ``printables``). To emulate the ``\b`` behavior of
  3221. regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``
  3222. will also match at the end of the string being parsed, or at the end
  3223. of a line.
  3224. """
  3225. def __init__(self, wordChars=printables):
  3226. super(WordEnd, self).__init__()
  3227. self.wordChars = set(wordChars)
  3228. self.skipWhitespace = False
  3229. self.errmsg = "Not at the end of a word"
  3230. def parseImpl(self, instring, loc, doActions=True):
  3231. instrlen = len(instring)
  3232. if instrlen > 0 and loc < instrlen:
  3233. if (instring[loc] in self.wordChars or
  3234. instring[loc - 1] not in self.wordChars):
  3235. raise ParseException(instring, loc, self.errmsg, self)
  3236. return loc, []
  3237. class ParseExpression(ParserElement):
  3238. """Abstract subclass of ParserElement, for combining and
  3239. post-processing parsed tokens.
  3240. """
  3241. def __init__(self, exprs, savelist=False):
  3242. super(ParseExpression, self).__init__(savelist)
  3243. if isinstance(exprs, _generatorType):
  3244. exprs = list(exprs)
  3245. if isinstance(exprs, basestring):
  3246. self.exprs = [self._literalStringClass(exprs)]
  3247. elif isinstance(exprs, ParserElement):
  3248. self.exprs = [exprs]
  3249. elif isinstance(exprs, Iterable):
  3250. exprs = list(exprs)
  3251. # if sequence of strings provided, wrap with Literal
  3252. if any(isinstance(expr, basestring) for expr in exprs):
  3253. exprs = (self._literalStringClass(e) if isinstance(e, basestring) else e for e in exprs)
  3254. self.exprs = list(exprs)
  3255. else:
  3256. try:
  3257. self.exprs = list(exprs)
  3258. except TypeError:
  3259. self.exprs = [exprs]
  3260. self.callPreparse = False
  3261. def append(self, other):
  3262. self.exprs.append(other)
  3263. self.strRepr = None
  3264. return self
  3265. def leaveWhitespace(self):
  3266. """Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on
  3267. all contained expressions."""
  3268. self.skipWhitespace = False
  3269. self.exprs = [e.copy() for e in self.exprs]
  3270. for e in self.exprs:
  3271. e.leaveWhitespace()
  3272. return self
  3273. def ignore(self, other):
  3274. if isinstance(other, Suppress):
  3275. if other not in self.ignoreExprs:
  3276. super(ParseExpression, self).ignore(other)
  3277. for e in self.exprs:
  3278. e.ignore(self.ignoreExprs[-1])
  3279. else:
  3280. super(ParseExpression, self).ignore(other)
  3281. for e in self.exprs:
  3282. e.ignore(self.ignoreExprs[-1])
  3283. return self
  3284. def __str__(self):
  3285. try:
  3286. return super(ParseExpression, self).__str__()
  3287. except Exception:
  3288. pass
  3289. if self.strRepr is None:
  3290. self.strRepr = "%s:(%s)" % (self.__class__.__name__, _ustr(self.exprs))
  3291. return self.strRepr
  3292. def streamline(self):
  3293. super(ParseExpression, self).streamline()
  3294. for e in self.exprs:
  3295. e.streamline()
  3296. # collapse nested And's of the form And(And(And(a, b), c), d) to And(a, b, c, d)
  3297. # but only if there are no parse actions or resultsNames on the nested And's
  3298. # (likewise for Or's and MatchFirst's)
  3299. if len(self.exprs) == 2:
  3300. other = self.exprs[0]
  3301. if (isinstance(other, self.__class__)
  3302. and not other.parseAction
  3303. and other.resultsName is None
  3304. and not other.debug):
  3305. self.exprs = other.exprs[:] + [self.exprs[1]]
  3306. self.strRepr = None
  3307. self.mayReturnEmpty |= other.mayReturnEmpty
  3308. self.mayIndexError |= other.mayIndexError
  3309. other = self.exprs[-1]
  3310. if (isinstance(other, self.__class__)
  3311. and not other.parseAction
  3312. and other.resultsName is None
  3313. and not other.debug):
  3314. self.exprs = self.exprs[:-1] + other.exprs[:]
  3315. self.strRepr = None
  3316. self.mayReturnEmpty |= other.mayReturnEmpty
  3317. self.mayIndexError |= other.mayIndexError
  3318. self.errmsg = "Expected " + _ustr(self)
  3319. return self
  3320. def validate(self, validateTrace=None):
  3321. tmp = (validateTrace if validateTrace is not None else [])[:] + [self]
  3322. for e in self.exprs:
  3323. e.validate(tmp)
  3324. self.checkRecursion([])
  3325. def copy(self):
  3326. ret = super(ParseExpression, self).copy()
  3327. ret.exprs = [e.copy() for e in self.exprs]
  3328. return ret
  3329. def _setResultsName(self, name, listAllMatches=False):
  3330. if __diag__.warn_ungrouped_named_tokens_in_collection:
  3331. for e in self.exprs:
  3332. if isinstance(e, ParserElement) and e.resultsName:
  3333. warnings.warn("{0}: setting results name {1!r} on {2} expression "
  3334. "collides with {3!r} on contained expression".format("warn_ungrouped_named_tokens_in_collection",
  3335. name,
  3336. type(self).__name__,
  3337. e.resultsName),
  3338. stacklevel=3)
  3339. return super(ParseExpression, self)._setResultsName(name, listAllMatches)
  3340. class And(ParseExpression):
  3341. """
  3342. Requires all given :class:`ParseExpression` s to be found in the given order.
  3343. Expressions may be separated by whitespace.
  3344. May be constructed using the ``'+'`` operator.
  3345. May also be constructed using the ``'-'`` operator, which will
  3346. suppress backtracking.
  3347. Example::
  3348. integer = Word(nums)
  3349. name_expr = OneOrMore(Word(alphas))
  3350. expr = And([integer("id"), name_expr("name"), integer("age")])
  3351. # more easily written as:
  3352. expr = integer("id") + name_expr("name") + integer("age")
  3353. """
  3354. class _ErrorStop(Empty):
  3355. def __init__(self, *args, **kwargs):
  3356. super(And._ErrorStop, self).__init__(*args, **kwargs)
  3357. self.name = '-'
  3358. self.leaveWhitespace()
  3359. def __init__(self, exprs, savelist=True):
  3360. exprs = list(exprs)
  3361. if exprs and Ellipsis in exprs:
  3362. tmp = []
  3363. for i, expr in enumerate(exprs):
  3364. if expr is Ellipsis:
  3365. if i < len(exprs) - 1:
  3366. skipto_arg = (Empty() + exprs[i + 1]).exprs[-1]
  3367. tmp.append(SkipTo(skipto_arg)("_skipped*"))
  3368. else:
  3369. raise Exception("cannot construct And with sequence ending in ...")
  3370. else:
  3371. tmp.append(expr)
  3372. exprs[:] = tmp
  3373. super(And, self).__init__(exprs, savelist)
  3374. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3375. self.setWhitespaceChars(self.exprs[0].whiteChars)
  3376. self.skipWhitespace = self.exprs[0].skipWhitespace
  3377. self.callPreparse = True
  3378. def streamline(self):
  3379. # collapse any _PendingSkip's
  3380. if self.exprs:
  3381. if any(isinstance(e, ParseExpression) and e.exprs and isinstance(e.exprs[-1], _PendingSkip)
  3382. for e in self.exprs[:-1]):
  3383. for i, e in enumerate(self.exprs[:-1]):
  3384. if e is None:
  3385. continue
  3386. if (isinstance(e, ParseExpression)
  3387. and e.exprs and isinstance(e.exprs[-1], _PendingSkip)):
  3388. e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]
  3389. self.exprs[i + 1] = None
  3390. self.exprs = [e for e in self.exprs if e is not None]
  3391. super(And, self).streamline()
  3392. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3393. return self
  3394. def parseImpl(self, instring, loc, doActions=True):
  3395. # pass False as last arg to _parse for first element, since we already
  3396. # pre-parsed the string as part of our And pre-parsing
  3397. loc, resultlist = self.exprs[0]._parse(instring, loc, doActions, callPreParse=False)
  3398. errorStop = False
  3399. for e in self.exprs[1:]:
  3400. if isinstance(e, And._ErrorStop):
  3401. errorStop = True
  3402. continue
  3403. if errorStop:
  3404. try:
  3405. loc, exprtokens = e._parse(instring, loc, doActions)
  3406. except ParseSyntaxException:
  3407. raise
  3408. except ParseBaseException as pe:
  3409. pe.__traceback__ = None
  3410. raise ParseSyntaxException._from_exception(pe)
  3411. except IndexError:
  3412. raise ParseSyntaxException(instring, len(instring), self.errmsg, self)
  3413. else:
  3414. loc, exprtokens = e._parse(instring, loc, doActions)
  3415. if exprtokens or exprtokens.haskeys():
  3416. resultlist += exprtokens
  3417. return loc, resultlist
  3418. def __iadd__(self, other):
  3419. if isinstance(other, basestring):
  3420. other = self._literalStringClass(other)
  3421. return self.append(other) # And([self, other])
  3422. def checkRecursion(self, parseElementList):
  3423. subRecCheckList = parseElementList[:] + [self]
  3424. for e in self.exprs:
  3425. e.checkRecursion(subRecCheckList)
  3426. if not e.mayReturnEmpty:
  3427. break
  3428. def __str__(self):
  3429. if hasattr(self, "name"):
  3430. return self.name
  3431. if self.strRepr is None:
  3432. self.strRepr = "{" + " ".join(_ustr(e) for e in self.exprs) + "}"
  3433. return self.strRepr
  3434. class Or(ParseExpression):
  3435. """Requires that at least one :class:`ParseExpression` is found. If
  3436. two expressions match, the expression that matches the longest
  3437. string will be used. May be constructed using the ``'^'``
  3438. operator.
  3439. Example::
  3440. # construct Or using '^' operator
  3441. number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
  3442. print(number.searchString("123 3.1416 789"))
  3443. prints::
  3444. [['123'], ['3.1416'], ['789']]
  3445. """
  3446. def __init__(self, exprs, savelist=False):
  3447. super(Or, self).__init__(exprs, savelist)
  3448. if self.exprs:
  3449. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3450. else:
  3451. self.mayReturnEmpty = True
  3452. def streamline(self):
  3453. super(Or, self).streamline()
  3454. if __compat__.collect_all_And_tokens:
  3455. self.saveAsList = any(e.saveAsList for e in self.exprs)
  3456. return self
  3457. def parseImpl(self, instring, loc, doActions=True):
  3458. maxExcLoc = -1
  3459. maxException = None
  3460. matches = []
  3461. for e in self.exprs:
  3462. try:
  3463. loc2 = e.tryParse(instring, loc)
  3464. except ParseException as err:
  3465. err.__traceback__ = None
  3466. if err.loc > maxExcLoc:
  3467. maxException = err
  3468. maxExcLoc = err.loc
  3469. except IndexError:
  3470. if len(instring) > maxExcLoc:
  3471. maxException = ParseException(instring, len(instring), e.errmsg, self)
  3472. maxExcLoc = len(instring)
  3473. else:
  3474. # save match among all matches, to retry longest to shortest
  3475. matches.append((loc2, e))
  3476. if matches:
  3477. # re-evaluate all matches in descending order of length of match, in case attached actions
  3478. # might change whether or how much they match of the input.
  3479. matches.sort(key=itemgetter(0), reverse=True)
  3480. if not doActions:
  3481. # no further conditions or parse actions to change the selection of
  3482. # alternative, so the first match will be the best match
  3483. best_expr = matches[0][1]
  3484. return best_expr._parse(instring, loc, doActions)
  3485. longest = -1, None
  3486. for loc1, expr1 in matches:
  3487. if loc1 <= longest[0]:
  3488. # already have a longer match than this one will deliver, we are done
  3489. return longest
  3490. try:
  3491. loc2, toks = expr1._parse(instring, loc, doActions)
  3492. except ParseException as err:
  3493. err.__traceback__ = None
  3494. if err.loc > maxExcLoc:
  3495. maxException = err
  3496. maxExcLoc = err.loc
  3497. else:
  3498. if loc2 >= loc1:
  3499. return loc2, toks
  3500. # didn't match as much as before
  3501. elif loc2 > longest[0]:
  3502. longest = loc2, toks
  3503. if longest != (-1, None):
  3504. return longest
  3505. if maxException is not None:
  3506. maxException.msg = self.errmsg
  3507. raise maxException
  3508. else:
  3509. raise ParseException(instring, loc, "no defined alternatives to match", self)
  3510. def __ixor__(self, other):
  3511. if isinstance(other, basestring):
  3512. other = self._literalStringClass(other)
  3513. return self.append(other) # Or([self, other])
  3514. def __str__(self):
  3515. if hasattr(self, "name"):
  3516. return self.name
  3517. if self.strRepr is None:
  3518. self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}"
  3519. return self.strRepr
  3520. def checkRecursion(self, parseElementList):
  3521. subRecCheckList = parseElementList[:] + [self]
  3522. for e in self.exprs:
  3523. e.checkRecursion(subRecCheckList)
  3524. def _setResultsName(self, name, listAllMatches=False):
  3525. if (not __compat__.collect_all_And_tokens
  3526. and __diag__.warn_multiple_tokens_in_named_alternation):
  3527. if any(isinstance(e, And) for e in self.exprs):
  3528. warnings.warn("{0}: setting results name {1!r} on {2} expression "
  3529. "may only return a single token for an And alternative, "
  3530. "in future will return the full list of tokens".format(
  3531. "warn_multiple_tokens_in_named_alternation", name, type(self).__name__),
  3532. stacklevel=3)
  3533. return super(Or, self)._setResultsName(name, listAllMatches)
  3534. class MatchFirst(ParseExpression):
  3535. """Requires that at least one :class:`ParseExpression` is found. If
  3536. two expressions match, the first one listed is the one that will
  3537. match. May be constructed using the ``'|'`` operator.
  3538. Example::
  3539. # construct MatchFirst using '|' operator
  3540. # watch the order of expressions to match
  3541. number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
  3542. print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']]
  3543. # put more selective expression first
  3544. number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
  3545. print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']]
  3546. """
  3547. def __init__(self, exprs, savelist=False):
  3548. super(MatchFirst, self).__init__(exprs, savelist)
  3549. if self.exprs:
  3550. self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
  3551. else:
  3552. self.mayReturnEmpty = True
  3553. def streamline(self):
  3554. super(MatchFirst, self).streamline()
  3555. if __compat__.collect_all_And_tokens:
  3556. self.saveAsList = any(e.saveAsList for e in self.exprs)
  3557. return self
  3558. def parseImpl(self, instring, loc, doActions=True):
  3559. maxExcLoc = -1
  3560. maxException = None
  3561. for e in self.exprs:
  3562. try:
  3563. ret = e._parse(instring, loc, doActions)
  3564. return ret
  3565. except ParseException as err:
  3566. if err.loc > maxExcLoc:
  3567. maxException = err
  3568. maxExcLoc = err.loc
  3569. except IndexError:
  3570. if len(instring) > maxExcLoc:
  3571. maxException = ParseException(instring, len(instring), e.errmsg, self)
  3572. maxExcLoc = len(instring)
  3573. # only got here if no expression matched, raise exception for match that made it the furthest
  3574. else:
  3575. if maxException is not None:
  3576. maxException.msg = self.errmsg
  3577. raise maxException
  3578. else:
  3579. raise ParseException(instring, loc, "no defined alternatives to match", self)
  3580. def __ior__(self, other):
  3581. if isinstance(other, basestring):
  3582. other = self._literalStringClass(other)
  3583. return self.append(other) # MatchFirst([self, other])
  3584. def __str__(self):
  3585. if hasattr(self, "name"):
  3586. return self.name
  3587. if self.strRepr is None:
  3588. self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}"
  3589. return self.strRepr
  3590. def checkRecursion(self, parseElementList):
  3591. subRecCheckList = parseElementList[:] + [self]
  3592. for e in self.exprs:
  3593. e.checkRecursion(subRecCheckList)
  3594. def _setResultsName(self, name, listAllMatches=False):
  3595. if (not __compat__.collect_all_And_tokens
  3596. and __diag__.warn_multiple_tokens_in_named_alternation):
  3597. if any(isinstance(e, And) for e in self.exprs):
  3598. warnings.warn("{0}: setting results name {1!r} on {2} expression "
  3599. "may only return a single token for an And alternative, "
  3600. "in future will return the full list of tokens".format(
  3601. "warn_multiple_tokens_in_named_alternation", name, type(self).__name__),
  3602. stacklevel=3)
  3603. return super(MatchFirst, self)._setResultsName(name, listAllMatches)
  3604. class Each(ParseExpression):
  3605. """Requires all given :class:`ParseExpression` s to be found, but in
  3606. any order. Expressions may be separated by whitespace.
  3607. May be constructed using the ``'&'`` operator.
  3608. Example::
  3609. color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
  3610. shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
  3611. integer = Word(nums)
  3612. shape_attr = "shape:" + shape_type("shape")
  3613. posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
  3614. color_attr = "color:" + color("color")
  3615. size_attr = "size:" + integer("size")
  3616. # use Each (using operator '&') to accept attributes in any order
  3617. # (shape and posn are required, color and size are optional)
  3618. shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr)
  3619. shape_spec.runTests('''
  3620. shape: SQUARE color: BLACK posn: 100, 120
  3621. shape: CIRCLE size: 50 color: BLUE posn: 50,80
  3622. color:GREEN size:20 shape:TRIANGLE posn:20,40
  3623. '''
  3624. )
  3625. prints::
  3626. shape: SQUARE color: BLACK posn: 100, 120
  3627. ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
  3628. - color: BLACK
  3629. - posn: ['100', ',', '120']
  3630. - x: 100
  3631. - y: 120
  3632. - shape: SQUARE
  3633. shape: CIRCLE size: 50 color: BLUE posn: 50,80
  3634. ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
  3635. - color: BLUE
  3636. - posn: ['50', ',', '80']
  3637. - x: 50
  3638. - y: 80
  3639. - shape: CIRCLE
  3640. - size: 50
  3641. color: GREEN size: 20 shape: TRIANGLE posn: 20,40
  3642. ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
  3643. - color: GREEN
  3644. - posn: ['20', ',', '40']
  3645. - x: 20
  3646. - y: 40
  3647. - shape: TRIANGLE
  3648. - size: 20
  3649. """
  3650. def __init__(self, exprs, savelist=True):
  3651. super(Each, self).__init__(exprs, savelist)
  3652. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3653. self.skipWhitespace = True
  3654. self.initExprGroups = True
  3655. self.saveAsList = True
  3656. def streamline(self):
  3657. super(Each, self).streamline()
  3658. self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
  3659. return self
  3660. def parseImpl(self, instring, loc, doActions=True):
  3661. if self.initExprGroups:
  3662. self.opt1map = dict((id(e.expr), e) for e in self.exprs if isinstance(e, Optional))
  3663. opt1 = [e.expr for e in self.exprs if isinstance(e, Optional)]
  3664. opt2 = [e for e in self.exprs if e.mayReturnEmpty and not isinstance(e, (Optional, Regex))]
  3665. self.optionals = opt1 + opt2
  3666. self.multioptionals = [e.expr for e in self.exprs if isinstance(e, ZeroOrMore)]
  3667. self.multirequired = [e.expr for e in self.exprs if isinstance(e, OneOrMore)]
  3668. self.required = [e for e in self.exprs if not isinstance(e, (Optional, ZeroOrMore, OneOrMore))]
  3669. self.required += self.multirequired
  3670. self.initExprGroups = False
  3671. tmpLoc = loc
  3672. tmpReqd = self.required[:]
  3673. tmpOpt = self.optionals[:]
  3674. matchOrder = []
  3675. keepMatching = True
  3676. while keepMatching:
  3677. tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
  3678. failed = []
  3679. for e in tmpExprs:
  3680. try:
  3681. tmpLoc = e.tryParse(instring, tmpLoc)
  3682. except ParseException:
  3683. failed.append(e)
  3684. else:
  3685. matchOrder.append(self.opt1map.get(id(e), e))
  3686. if e in tmpReqd:
  3687. tmpReqd.remove(e)
  3688. elif e in tmpOpt:
  3689. tmpOpt.remove(e)
  3690. if len(failed) == len(tmpExprs):
  3691. keepMatching = False
  3692. if tmpReqd:
  3693. missing = ", ".join(_ustr(e) for e in tmpReqd)
  3694. raise ParseException(instring, loc, "Missing one or more required elements (%s)" % missing)
  3695. # add any unmatched Optionals, in case they have default values defined
  3696. matchOrder += [e for e in self.exprs if isinstance(e, Optional) and e.expr in tmpOpt]
  3697. resultlist = []
  3698. for e in matchOrder:
  3699. loc, results = e._parse(instring, loc, doActions)
  3700. resultlist.append(results)
  3701. finalResults = sum(resultlist, ParseResults([]))
  3702. return loc, finalResults
  3703. def __str__(self):
  3704. if hasattr(self, "name"):
  3705. return self.name
  3706. if self.strRepr is None:
  3707. self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}"
  3708. return self.strRepr
  3709. def checkRecursion(self, parseElementList):
  3710. subRecCheckList = parseElementList[:] + [self]
  3711. for e in self.exprs:
  3712. e.checkRecursion(subRecCheckList)
  3713. class ParseElementEnhance(ParserElement):
  3714. """Abstract subclass of :class:`ParserElement`, for combining and
  3715. post-processing parsed tokens.
  3716. """
  3717. def __init__(self, expr, savelist=False):
  3718. super(ParseElementEnhance, self).__init__(savelist)
  3719. if isinstance(expr, basestring):
  3720. if issubclass(self._literalStringClass, Token):
  3721. expr = self._literalStringClass(expr)
  3722. else:
  3723. expr = self._literalStringClass(Literal(expr))
  3724. self.expr = expr
  3725. self.strRepr = None
  3726. if expr is not None:
  3727. self.mayIndexError = expr.mayIndexError
  3728. self.mayReturnEmpty = expr.mayReturnEmpty
  3729. self.setWhitespaceChars(expr.whiteChars)
  3730. self.skipWhitespace = expr.skipWhitespace
  3731. self.saveAsList = expr.saveAsList
  3732. self.callPreparse = expr.callPreparse
  3733. self.ignoreExprs.extend(expr.ignoreExprs)
  3734. def parseImpl(self, instring, loc, doActions=True):
  3735. if self.expr is not None:
  3736. return self.expr._parse(instring, loc, doActions, callPreParse=False)
  3737. else:
  3738. raise ParseException("", loc, self.errmsg, self)
  3739. def leaveWhitespace(self):
  3740. self.skipWhitespace = False
  3741. self.expr = self.expr.copy()
  3742. if self.expr is not None:
  3743. self.expr.leaveWhitespace()
  3744. return self
  3745. def ignore(self, other):
  3746. if isinstance(other, Suppress):
  3747. if other not in self.ignoreExprs:
  3748. super(ParseElementEnhance, self).ignore(other)
  3749. if self.expr is not None:
  3750. self.expr.ignore(self.ignoreExprs[-1])
  3751. else:
  3752. super(ParseElementEnhance, self).ignore(other)
  3753. if self.expr is not None:
  3754. self.expr.ignore(self.ignoreExprs[-1])
  3755. return self
  3756. def streamline(self):
  3757. super(ParseElementEnhance, self).streamline()
  3758. if self.expr is not None:
  3759. self.expr.streamline()
  3760. return self
  3761. def checkRecursion(self, parseElementList):
  3762. if self in parseElementList:
  3763. raise RecursiveGrammarException(parseElementList + [self])
  3764. subRecCheckList = parseElementList[:] + [self]
  3765. if self.expr is not None:
  3766. self.expr.checkRecursion(subRecCheckList)
  3767. def validate(self, validateTrace=None):
  3768. if validateTrace is None:
  3769. validateTrace = []
  3770. tmp = validateTrace[:] + [self]
  3771. if self.expr is not None:
  3772. self.expr.validate(tmp)
  3773. self.checkRecursion([])
  3774. def __str__(self):
  3775. try:
  3776. return super(ParseElementEnhance, self).__str__()
  3777. except Exception:
  3778. pass
  3779. if self.strRepr is None and self.expr is not None:
  3780. self.strRepr = "%s:(%s)" % (self.__class__.__name__, _ustr(self.expr))
  3781. return self.strRepr
  3782. class FollowedBy(ParseElementEnhance):
  3783. """Lookahead matching of the given parse expression.
  3784. ``FollowedBy`` does *not* advance the parsing position within
  3785. the input string, it only verifies that the specified parse
  3786. expression matches at the current position. ``FollowedBy``
  3787. always returns a null token list. If any results names are defined
  3788. in the lookahead expression, those *will* be returned for access by
  3789. name.
  3790. Example::
  3791. # use FollowedBy to match a label only if it is followed by a ':'
  3792. data_word = Word(alphas)
  3793. label = data_word + FollowedBy(':')
  3794. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
  3795. OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint()
  3796. prints::
  3797. [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
  3798. """
  3799. def __init__(self, expr):
  3800. super(FollowedBy, self).__init__(expr)
  3801. self.mayReturnEmpty = True
  3802. def parseImpl(self, instring, loc, doActions=True):
  3803. # by using self._expr.parse and deleting the contents of the returned ParseResults list
  3804. # we keep any named results that were defined in the FollowedBy expression
  3805. _, ret = self.expr._parse(instring, loc, doActions=doActions)
  3806. del ret[:]
  3807. return loc, ret
  3808. class PrecededBy(ParseElementEnhance):
  3809. """Lookbehind matching of the given parse expression.
  3810. ``PrecededBy`` does not advance the parsing position within the
  3811. input string, it only verifies that the specified parse expression
  3812. matches prior to the current position. ``PrecededBy`` always
  3813. returns a null token list, but if a results name is defined on the
  3814. given expression, it is returned.
  3815. Parameters:
  3816. - expr - expression that must match prior to the current parse
  3817. location
  3818. - retreat - (default= ``None``) - (int) maximum number of characters
  3819. to lookbehind prior to the current parse location
  3820. If the lookbehind expression is a string, Literal, Keyword, or
  3821. a Word or CharsNotIn with a specified exact or maximum length, then
  3822. the retreat parameter is not required. Otherwise, retreat must be
  3823. specified to give a maximum number of characters to look back from
  3824. the current parse position for a lookbehind match.
  3825. Example::
  3826. # VB-style variable names with type prefixes
  3827. int_var = PrecededBy("#") + pyparsing_common.identifier
  3828. str_var = PrecededBy("$") + pyparsing_common.identifier
  3829. """
  3830. def __init__(self, expr, retreat=None):
  3831. super(PrecededBy, self).__init__(expr)
  3832. self.expr = self.expr().leaveWhitespace()
  3833. self.mayReturnEmpty = True
  3834. self.mayIndexError = False
  3835. self.exact = False
  3836. if isinstance(expr, str):
  3837. retreat = len(expr)
  3838. self.exact = True
  3839. elif isinstance(expr, (Literal, Keyword)):
  3840. retreat = expr.matchLen
  3841. self.exact = True
  3842. elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:
  3843. retreat = expr.maxLen
  3844. self.exact = True
  3845. elif isinstance(expr, _PositionToken):
  3846. retreat = 0
  3847. self.exact = True
  3848. self.retreat = retreat
  3849. self.errmsg = "not preceded by " + str(expr)
  3850. self.skipWhitespace = False
  3851. self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))
  3852. def parseImpl(self, instring, loc=0, doActions=True):
  3853. if self.exact:
  3854. if loc < self.retreat:
  3855. raise ParseException(instring, loc, self.errmsg)
  3856. start = loc - self.retreat
  3857. _, ret = self.expr._parse(instring, start)
  3858. else:
  3859. # retreat specified a maximum lookbehind window, iterate
  3860. test_expr = self.expr + StringEnd()
  3861. instring_slice = instring[max(0, loc - self.retreat):loc]
  3862. last_expr = ParseException(instring, loc, self.errmsg)
  3863. for offset in range(1, min(loc, self.retreat + 1)+1):
  3864. try:
  3865. # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))
  3866. _, ret = test_expr._parse(instring_slice, len(instring_slice) - offset)
  3867. except ParseBaseException as pbe:
  3868. last_expr = pbe
  3869. else:
  3870. break
  3871. else:
  3872. raise last_expr
  3873. return loc, ret
  3874. class NotAny(ParseElementEnhance):
  3875. """Lookahead to disallow matching with the given parse expression.
  3876. ``NotAny`` does *not* advance the parsing position within the
  3877. input string, it only verifies that the specified parse expression
  3878. does *not* match at the current position. Also, ``NotAny`` does
  3879. *not* skip over leading whitespace. ``NotAny`` always returns
  3880. a null token list. May be constructed using the '~' operator.
  3881. Example::
  3882. AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split())
  3883. # take care not to mistake keywords for identifiers
  3884. ident = ~(AND | OR | NOT) + Word(alphas)
  3885. boolean_term = Optional(NOT) + ident
  3886. # very crude boolean expression - to support parenthesis groups and
  3887. # operation hierarchy, use infixNotation
  3888. boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term)
  3889. # integers that are followed by "." are actually floats
  3890. integer = Word(nums) + ~Char(".")
  3891. """
  3892. def __init__(self, expr):
  3893. super(NotAny, self).__init__(expr)
  3894. # ~ self.leaveWhitespace()
  3895. self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
  3896. self.mayReturnEmpty = True
  3897. self.errmsg = "Found unwanted token, " + _ustr(self.expr)
  3898. def parseImpl(self, instring, loc, doActions=True):
  3899. if self.expr.canParseNext(instring, loc):
  3900. raise ParseException(instring, loc, self.errmsg, self)
  3901. return loc, []
  3902. def __str__(self):
  3903. if hasattr(self, "name"):
  3904. return self.name
  3905. if self.strRepr is None:
  3906. self.strRepr = "~{" + _ustr(self.expr) + "}"
  3907. return self.strRepr
  3908. class _MultipleMatch(ParseElementEnhance):
  3909. def __init__(self, expr, stopOn=None):
  3910. super(_MultipleMatch, self).__init__(expr)
  3911. self.saveAsList = True
  3912. ender = stopOn
  3913. if isinstance(ender, basestring):
  3914. ender = self._literalStringClass(ender)
  3915. self.stopOn(ender)
  3916. def stopOn(self, ender):
  3917. if isinstance(ender, basestring):
  3918. ender = self._literalStringClass(ender)
  3919. self.not_ender = ~ender if ender is not None else None
  3920. return self
  3921. def parseImpl(self, instring, loc, doActions=True):
  3922. self_expr_parse = self.expr._parse
  3923. self_skip_ignorables = self._skipIgnorables
  3924. check_ender = self.not_ender is not None
  3925. if check_ender:
  3926. try_not_ender = self.not_ender.tryParse
  3927. # must be at least one (but first see if we are the stopOn sentinel;
  3928. # if so, fail)
  3929. if check_ender:
  3930. try_not_ender(instring, loc)
  3931. loc, tokens = self_expr_parse(instring, loc, doActions, callPreParse=False)
  3932. try:
  3933. hasIgnoreExprs = (not not self.ignoreExprs)
  3934. while 1:
  3935. if check_ender:
  3936. try_not_ender(instring, loc)
  3937. if hasIgnoreExprs:
  3938. preloc = self_skip_ignorables(instring, loc)
  3939. else:
  3940. preloc = loc
  3941. loc, tmptokens = self_expr_parse(instring, preloc, doActions)
  3942. if tmptokens or tmptokens.haskeys():
  3943. tokens += tmptokens
  3944. except (ParseException, IndexError):
  3945. pass
  3946. return loc, tokens
  3947. def _setResultsName(self, name, listAllMatches=False):
  3948. if __diag__.warn_ungrouped_named_tokens_in_collection:
  3949. for e in [self.expr] + getattr(self.expr, 'exprs', []):
  3950. if isinstance(e, ParserElement) and e.resultsName:
  3951. warnings.warn("{0}: setting results name {1!r} on {2} expression "
  3952. "collides with {3!r} on contained expression".format("warn_ungrouped_named_tokens_in_collection",
  3953. name,
  3954. type(self).__name__,
  3955. e.resultsName),
  3956. stacklevel=3)
  3957. return super(_MultipleMatch, self)._setResultsName(name, listAllMatches)
  3958. class OneOrMore(_MultipleMatch):
  3959. """Repetition of one or more of the given expression.
  3960. Parameters:
  3961. - expr - expression that must match one or more times
  3962. - stopOn - (default= ``None``) - expression for a terminating sentinel
  3963. (only required if the sentinel would ordinarily match the repetition
  3964. expression)
  3965. Example::
  3966. data_word = Word(alphas)
  3967. label = data_word + FollowedBy(':')
  3968. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
  3969. text = "shape: SQUARE posn: upper left color: BLACK"
  3970. OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]
  3971. # use stopOn attribute for OneOrMore to avoid reading label string as part of the data
  3972. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
  3973. OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
  3974. # could also be written as
  3975. (attr_expr * (1,)).parseString(text).pprint()
  3976. """
  3977. def __str__(self):
  3978. if hasattr(self, "name"):
  3979. return self.name
  3980. if self.strRepr is None:
  3981. self.strRepr = "{" + _ustr(self.expr) + "}..."
  3982. return self.strRepr
  3983. class ZeroOrMore(_MultipleMatch):
  3984. """Optional repetition of zero or more of the given expression.
  3985. Parameters:
  3986. - expr - expression that must match zero or more times
  3987. - stopOn - (default= ``None``) - expression for a terminating sentinel
  3988. (only required if the sentinel would ordinarily match the repetition
  3989. expression)
  3990. Example: similar to :class:`OneOrMore`
  3991. """
  3992. def __init__(self, expr, stopOn=None):
  3993. super(ZeroOrMore, self).__init__(expr, stopOn=stopOn)
  3994. self.mayReturnEmpty = True
  3995. def parseImpl(self, instring, loc, doActions=True):
  3996. try:
  3997. return super(ZeroOrMore, self).parseImpl(instring, loc, doActions)
  3998. except (ParseException, IndexError):
  3999. return loc, []
  4000. def __str__(self):
  4001. if hasattr(self, "name"):
  4002. return self.name
  4003. if self.strRepr is None:
  4004. self.strRepr = "[" + _ustr(self.expr) + "]..."
  4005. return self.strRepr
  4006. class _NullToken(object):
  4007. def __bool__(self):
  4008. return False
  4009. __nonzero__ = __bool__
  4010. def __str__(self):
  4011. return ""
  4012. class Optional(ParseElementEnhance):
  4013. """Optional matching of the given expression.
  4014. Parameters:
  4015. - expr - expression that must match zero or more times
  4016. - default (optional) - value to be returned if the optional expression is not found.
  4017. Example::
  4018. # US postal code can be a 5-digit zip, plus optional 4-digit qualifier
  4019. zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4)))
  4020. zip.runTests('''
  4021. # traditional ZIP code
  4022. 12345
  4023. # ZIP+4 form
  4024. 12101-0001
  4025. # invalid ZIP
  4026. 98765-
  4027. ''')
  4028. prints::
  4029. # traditional ZIP code
  4030. 12345
  4031. ['12345']
  4032. # ZIP+4 form
  4033. 12101-0001
  4034. ['12101-0001']
  4035. # invalid ZIP
  4036. 98765-
  4037. ^
  4038. FAIL: Expected end of text (at char 5), (line:1, col:6)
  4039. """
  4040. __optionalNotMatched = _NullToken()
  4041. def __init__(self, expr, default=__optionalNotMatched):
  4042. super(Optional, self).__init__(expr, savelist=False)
  4043. self.saveAsList = self.expr.saveAsList
  4044. self.defaultValue = default
  4045. self.mayReturnEmpty = True
  4046. def parseImpl(self, instring, loc, doActions=True):
  4047. try:
  4048. loc, tokens = self.expr._parse(instring, loc, doActions, callPreParse=False)
  4049. except (ParseException, IndexError):
  4050. if self.defaultValue is not self.__optionalNotMatched:
  4051. if self.expr.resultsName:
  4052. tokens = ParseResults([self.defaultValue])
  4053. tokens[self.expr.resultsName] = self.defaultValue
  4054. else:
  4055. tokens = [self.defaultValue]
  4056. else:
  4057. tokens = []
  4058. return loc, tokens
  4059. def __str__(self):
  4060. if hasattr(self, "name"):
  4061. return self.name
  4062. if self.strRepr is None:
  4063. self.strRepr = "[" + _ustr(self.expr) + "]"
  4064. return self.strRepr
  4065. class SkipTo(ParseElementEnhance):
  4066. """Token for skipping over all undefined text until the matched
  4067. expression is found.
  4068. Parameters:
  4069. - expr - target expression marking the end of the data to be skipped
  4070. - include - (default= ``False``) if True, the target expression is also parsed
  4071. (the skipped text and target expression are returned as a 2-element list).
  4072. - ignore - (default= ``None``) used to define grammars (typically quoted strings and
  4073. comments) that might contain false matches to the target expression
  4074. - failOn - (default= ``None``) define expressions that are not allowed to be
  4075. included in the skipped test; if found before the target expression is found,
  4076. the SkipTo is not a match
  4077. Example::
  4078. report = '''
  4079. Outstanding Issues Report - 1 Jan 2000
  4080. # | Severity | Description | Days Open
  4081. -----+----------+-------------------------------------------+-----------
  4082. 101 | Critical | Intermittent system crash | 6
  4083. 94 | Cosmetic | Spelling error on Login ('log|n') | 14
  4084. 79 | Minor | System slow when running too many reports | 47
  4085. '''
  4086. integer = Word(nums)
  4087. SEP = Suppress('|')
  4088. # use SkipTo to simply match everything up until the next SEP
  4089. # - ignore quoted strings, so that a '|' character inside a quoted string does not match
  4090. # - parse action will call token.strip() for each matched token, i.e., the description body
  4091. string_data = SkipTo(SEP, ignore=quotedString)
  4092. string_data.setParseAction(tokenMap(str.strip))
  4093. ticket_expr = (integer("issue_num") + SEP
  4094. + string_data("sev") + SEP
  4095. + string_data("desc") + SEP
  4096. + integer("days_open"))
  4097. for tkt in ticket_expr.searchString(report):
  4098. print tkt.dump()
  4099. prints::
  4100. ['101', 'Critical', 'Intermittent system crash', '6']
  4101. - days_open: 6
  4102. - desc: Intermittent system crash
  4103. - issue_num: 101
  4104. - sev: Critical
  4105. ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
  4106. - days_open: 14
  4107. - desc: Spelling error on Login ('log|n')
  4108. - issue_num: 94
  4109. - sev: Cosmetic
  4110. ['79', 'Minor', 'System slow when running too many reports', '47']
  4111. - days_open: 47
  4112. - desc: System slow when running too many reports
  4113. - issue_num: 79
  4114. - sev: Minor
  4115. """
  4116. def __init__(self, other, include=False, ignore=None, failOn=None):
  4117. super(SkipTo, self).__init__(other)
  4118. self.ignoreExpr = ignore
  4119. self.mayReturnEmpty = True
  4120. self.mayIndexError = False
  4121. self.includeMatch = include
  4122. self.saveAsList = False
  4123. if isinstance(failOn, basestring):
  4124. self.failOn = self._literalStringClass(failOn)
  4125. else:
  4126. self.failOn = failOn
  4127. self.errmsg = "No match found for " + _ustr(self.expr)
  4128. def parseImpl(self, instring, loc, doActions=True):
  4129. startloc = loc
  4130. instrlen = len(instring)
  4131. expr = self.expr
  4132. expr_parse = self.expr._parse
  4133. self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None
  4134. self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None
  4135. tmploc = loc
  4136. while tmploc <= instrlen:
  4137. if self_failOn_canParseNext is not None:
  4138. # break if failOn expression matches
  4139. if self_failOn_canParseNext(instring, tmploc):
  4140. break
  4141. if self_ignoreExpr_tryParse is not None:
  4142. # advance past ignore expressions
  4143. while 1:
  4144. try:
  4145. tmploc = self_ignoreExpr_tryParse(instring, tmploc)
  4146. except ParseBaseException:
  4147. break
  4148. try:
  4149. expr_parse(instring, tmploc, doActions=False, callPreParse=False)
  4150. except (ParseException, IndexError):
  4151. # no match, advance loc in string
  4152. tmploc += 1
  4153. else:
  4154. # matched skipto expr, done
  4155. break
  4156. else:
  4157. # ran off the end of the input string without matching skipto expr, fail
  4158. raise ParseException(instring, loc, self.errmsg, self)
  4159. # build up return values
  4160. loc = tmploc
  4161. skiptext = instring[startloc:loc]
  4162. skipresult = ParseResults(skiptext)
  4163. if self.includeMatch:
  4164. loc, mat = expr_parse(instring, loc, doActions, callPreParse=False)
  4165. skipresult += mat
  4166. return loc, skipresult
  4167. class Forward(ParseElementEnhance):
  4168. """Forward declaration of an expression to be defined later -
  4169. used for recursive grammars, such as algebraic infix notation.
  4170. When the expression is known, it is assigned to the ``Forward``
  4171. variable using the '<<' operator.
  4172. Note: take care when assigning to ``Forward`` not to overlook
  4173. precedence of operators.
  4174. Specifically, '|' has a lower precedence than '<<', so that::
  4175. fwdExpr << a | b | c
  4176. will actually be evaluated as::
  4177. (fwdExpr << a) | b | c
  4178. thereby leaving b and c out as parseable alternatives. It is recommended that you
  4179. explicitly group the values inserted into the ``Forward``::
  4180. fwdExpr << (a | b | c)
  4181. Converting to use the '<<=' operator instead will avoid this problem.
  4182. See :class:`ParseResults.pprint` for an example of a recursive
  4183. parser created using ``Forward``.
  4184. """
  4185. def __init__(self, other=None):
  4186. super(Forward, self).__init__(other, savelist=False)
  4187. def __lshift__(self, other):
  4188. if isinstance(other, basestring):
  4189. other = self._literalStringClass(other)
  4190. self.expr = other
  4191. self.strRepr = None
  4192. self.mayIndexError = self.expr.mayIndexError
  4193. self.mayReturnEmpty = self.expr.mayReturnEmpty
  4194. self.setWhitespaceChars(self.expr.whiteChars)
  4195. self.skipWhitespace = self.expr.skipWhitespace
  4196. self.saveAsList = self.expr.saveAsList
  4197. self.ignoreExprs.extend(self.expr.ignoreExprs)
  4198. return self
  4199. def __ilshift__(self, other):
  4200. return self << other
  4201. def leaveWhitespace(self):
  4202. self.skipWhitespace = False
  4203. return self
  4204. def streamline(self):
  4205. if not self.streamlined:
  4206. self.streamlined = True
  4207. if self.expr is not None:
  4208. self.expr.streamline()
  4209. return self
  4210. def validate(self, validateTrace=None):
  4211. if validateTrace is None:
  4212. validateTrace = []
  4213. if self not in validateTrace:
  4214. tmp = validateTrace[:] + [self]
  4215. if self.expr is not None:
  4216. self.expr.validate(tmp)
  4217. self.checkRecursion([])
  4218. def __str__(self):
  4219. if hasattr(self, "name"):
  4220. return self.name
  4221. if self.strRepr is not None:
  4222. return self.strRepr
  4223. # Avoid infinite recursion by setting a temporary strRepr
  4224. self.strRepr = ": ..."
  4225. # Use the string representation of main expression.
  4226. retString = '...'
  4227. try:
  4228. if self.expr is not None:
  4229. retString = _ustr(self.expr)[:1000]
  4230. else:
  4231. retString = "None"
  4232. finally:
  4233. self.strRepr = self.__class__.__name__ + ": " + retString
  4234. return self.strRepr
  4235. def copy(self):
  4236. if self.expr is not None:
  4237. return super(Forward, self).copy()
  4238. else:
  4239. ret = Forward()
  4240. ret <<= self
  4241. return ret
  4242. def _setResultsName(self, name, listAllMatches=False):
  4243. if __diag__.warn_name_set_on_empty_Forward:
  4244. if self.expr is None:
  4245. warnings.warn("{0}: setting results name {0!r} on {1} expression "
  4246. "that has no contained expression".format("warn_name_set_on_empty_Forward",
  4247. name,
  4248. type(self).__name__),
  4249. stacklevel=3)
  4250. return super(Forward, self)._setResultsName(name, listAllMatches)
  4251. class TokenConverter(ParseElementEnhance):
  4252. """
  4253. Abstract subclass of :class:`ParseExpression`, for converting parsed results.
  4254. """
  4255. def __init__(self, expr, savelist=False):
  4256. super(TokenConverter, self).__init__(expr) # , savelist)
  4257. self.saveAsList = False
  4258. class Combine(TokenConverter):
  4259. """Converter to concatenate all matching tokens to a single string.
  4260. By default, the matching patterns must also be contiguous in the
  4261. input string; this can be disabled by specifying
  4262. ``'adjacent=False'`` in the constructor.
  4263. Example::
  4264. real = Word(nums) + '.' + Word(nums)
  4265. print(real.parseString('3.1416')) # -> ['3', '.', '1416']
  4266. # will also erroneously match the following
  4267. print(real.parseString('3. 1416')) # -> ['3', '.', '1416']
  4268. real = Combine(Word(nums) + '.' + Word(nums))
  4269. print(real.parseString('3.1416')) # -> ['3.1416']
  4270. # no match when there are internal spaces
  4271. print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...)
  4272. """
  4273. def __init__(self, expr, joinString="", adjacent=True):
  4274. super(Combine, self).__init__(expr)
  4275. # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
  4276. if adjacent:
  4277. self.leaveWhitespace()
  4278. self.adjacent = adjacent
  4279. self.skipWhitespace = True
  4280. self.joinString = joinString
  4281. self.callPreparse = True
  4282. def ignore(self, other):
  4283. if self.adjacent:
  4284. ParserElement.ignore(self, other)
  4285. else:
  4286. super(Combine, self).ignore(other)
  4287. return self
  4288. def postParse(self, instring, loc, tokenlist):
  4289. retToks = tokenlist.copy()
  4290. del retToks[:]
  4291. retToks += ParseResults(["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults)
  4292. if self.resultsName and retToks.haskeys():
  4293. return [retToks]
  4294. else:
  4295. return retToks
  4296. class Group(TokenConverter):
  4297. """Converter to return the matched tokens as a list - useful for
  4298. returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.
  4299. Example::
  4300. ident = Word(alphas)
  4301. num = Word(nums)
  4302. term = ident | num
  4303. func = ident + Optional(delimitedList(term))
  4304. print(func.parseString("fn a, b, 100")) # -> ['fn', 'a', 'b', '100']
  4305. func = ident + Group(Optional(delimitedList(term)))
  4306. print(func.parseString("fn a, b, 100")) # -> ['fn', ['a', 'b', '100']]
  4307. """
  4308. def __init__(self, expr):
  4309. super(Group, self).__init__(expr)
  4310. self.saveAsList = True
  4311. def postParse(self, instring, loc, tokenlist):
  4312. return [tokenlist]
  4313. class Dict(TokenConverter):
  4314. """Converter to return a repetitive expression as a list, but also
  4315. as a dictionary. Each element can also be referenced using the first
  4316. token in the expression as its key. Useful for tabular report
  4317. scraping when the first column can be used as a item key.
  4318. Example::
  4319. data_word = Word(alphas)
  4320. label = data_word + FollowedBy(':')
  4321. attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
  4322. text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
  4323. attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
  4324. # print attributes as plain groups
  4325. print(OneOrMore(attr_expr).parseString(text).dump())
  4326. # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
  4327. result = Dict(OneOrMore(Group(attr_expr))).parseString(text)
  4328. print(result.dump())
  4329. # access named fields as dict entries, or output as dict
  4330. print(result['shape'])
  4331. print(result.asDict())
  4332. prints::
  4333. ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
  4334. [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
  4335. - color: light blue
  4336. - posn: upper left
  4337. - shape: SQUARE
  4338. - texture: burlap
  4339. SQUARE
  4340. {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
  4341. See more examples at :class:`ParseResults` of accessing fields by results name.
  4342. """
  4343. def __init__(self, expr):
  4344. super(Dict, self).__init__(expr)
  4345. self.saveAsList = True
  4346. def postParse(self, instring, loc, tokenlist):
  4347. for i, tok in enumerate(tokenlist):
  4348. if len(tok) == 0:
  4349. continue
  4350. ikey = tok[0]
  4351. if isinstance(ikey, int):
  4352. ikey = _ustr(tok[0]).strip()
  4353. if len(tok) == 1:
  4354. tokenlist[ikey] = _ParseResultsWithOffset("", i)
  4355. elif len(tok) == 2 and not isinstance(tok[1], ParseResults):
  4356. tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)
  4357. else:
  4358. dictvalue = tok.copy() # ParseResults(i)
  4359. del dictvalue[0]
  4360. if len(dictvalue) != 1 or (isinstance(dictvalue, ParseResults) and dictvalue.haskeys()):
  4361. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)
  4362. else:
  4363. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)
  4364. if self.resultsName:
  4365. return [tokenlist]
  4366. else:
  4367. return tokenlist
  4368. class Suppress(TokenConverter):
  4369. """Converter for ignoring the results of a parsed expression.
  4370. Example::
  4371. source = "a, b, c,d"
  4372. wd = Word(alphas)
  4373. wd_list1 = wd + ZeroOrMore(',' + wd)
  4374. print(wd_list1.parseString(source))
  4375. # often, delimiters that are useful during parsing are just in the
  4376. # way afterward - use Suppress to keep them out of the parsed output
  4377. wd_list2 = wd + ZeroOrMore(Suppress(',') + wd)
  4378. print(wd_list2.parseString(source))
  4379. prints::
  4380. ['a', ',', 'b', ',', 'c', ',', 'd']
  4381. ['a', 'b', 'c', 'd']
  4382. (See also :class:`delimitedList`.)
  4383. """
  4384. def postParse(self, instring, loc, tokenlist):
  4385. return []
  4386. def suppress(self):
  4387. return self
  4388. class OnlyOnce(object):
  4389. """Wrapper for parse actions, to ensure they are only called once.
  4390. """
  4391. def __init__(self, methodCall):
  4392. self.callable = _trim_arity(methodCall)
  4393. self.called = False
  4394. def __call__(self, s, l, t):
  4395. if not self.called:
  4396. results = self.callable(s, l, t)
  4397. self.called = True
  4398. return results
  4399. raise ParseException(s, l, "")
  4400. def reset(self):
  4401. self.called = False
  4402. def traceParseAction(f):
  4403. """Decorator for debugging parse actions.
  4404. When the parse action is called, this decorator will print
  4405. ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``.
  4406. When the parse action completes, the decorator will print
  4407. ``"<<"`` followed by the returned value, or any exception that the parse action raised.
  4408. Example::
  4409. wd = Word(alphas)
  4410. @traceParseAction
  4411. def remove_duplicate_chars(tokens):
  4412. return ''.join(sorted(set(''.join(tokens))))
  4413. wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
  4414. print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
  4415. prints::
  4416. >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
  4417. <<leaving remove_duplicate_chars (ret: 'dfjkls')
  4418. ['dfjkls']
  4419. """
  4420. f = _trim_arity(f)
  4421. def z(*paArgs):
  4422. thisFunc = f.__name__
  4423. s, l, t = paArgs[-3:]
  4424. if len(paArgs) > 3:
  4425. thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
  4426. sys.stderr.write(">>entering %s(line: '%s', %d, %r)\n" % (thisFunc, line(l, s), l, t))
  4427. try:
  4428. ret = f(*paArgs)
  4429. except Exception as exc:
  4430. sys.stderr.write("<<leaving %s (exception: %s)\n" % (thisFunc, exc))
  4431. raise
  4432. sys.stderr.write("<<leaving %s (ret: %r)\n" % (thisFunc, ret))
  4433. return ret
  4434. try:
  4435. z.__name__ = f.__name__
  4436. except AttributeError:
  4437. pass
  4438. return z
  4439. #
  4440. # global helpers
  4441. #
  4442. def delimitedList(expr, delim=",", combine=False):
  4443. """Helper to define a delimited list of expressions - the delimiter
  4444. defaults to ','. By default, the list elements and delimiters can
  4445. have intervening whitespace, and comments, but this can be
  4446. overridden by passing ``combine=True`` in the constructor. If
  4447. ``combine`` is set to ``True``, the matching tokens are
  4448. returned as a single token string, with the delimiters included;
  4449. otherwise, the matching tokens are returned as a list of tokens,
  4450. with the delimiters suppressed.
  4451. Example::
  4452. delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
  4453. delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
  4454. """
  4455. dlName = _ustr(expr) + " [" + _ustr(delim) + " " + _ustr(expr) + "]..."
  4456. if combine:
  4457. return Combine(expr + ZeroOrMore(delim + expr)).setName(dlName)
  4458. else:
  4459. return (expr + ZeroOrMore(Suppress(delim) + expr)).setName(dlName)
  4460. def countedArray(expr, intExpr=None):
  4461. """Helper to define a counted list of expressions.
  4462. This helper defines a pattern of the form::
  4463. integer expr expr expr...
  4464. where the leading integer tells how many expr expressions follow.
  4465. The matched tokens returns the array of expr tokens as a list - the
  4466. leading count token is suppressed.
  4467. If ``intExpr`` is specified, it should be a pyparsing expression
  4468. that produces an integer value.
  4469. Example::
  4470. countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd']
  4471. # in this parser, the leading integer value is given in binary,
  4472. # '10' indicating that 2 values are in the array
  4473. binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2))
  4474. countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd']
  4475. """
  4476. arrayExpr = Forward()
  4477. def countFieldParseAction(s, l, t):
  4478. n = t[0]
  4479. arrayExpr << (n and Group(And([expr] * n)) or Group(empty))
  4480. return []
  4481. if intExpr is None:
  4482. intExpr = Word(nums).setParseAction(lambda t: int(t[0]))
  4483. else:
  4484. intExpr = intExpr.copy()
  4485. intExpr.setName("arrayLen")
  4486. intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
  4487. return (intExpr + arrayExpr).setName('(len) ' + _ustr(expr) + '...')
  4488. def _flatten(L):
  4489. ret = []
  4490. for i in L:
  4491. if isinstance(i, list):
  4492. ret.extend(_flatten(i))
  4493. else:
  4494. ret.append(i)
  4495. return ret
  4496. def matchPreviousLiteral(expr):
  4497. """Helper to define an expression that is indirectly defined from
  4498. the tokens matched in a previous expression, that is, it looks for
  4499. a 'repeat' of a previous expression. For example::
  4500. first = Word(nums)
  4501. second = matchPreviousLiteral(first)
  4502. matchExpr = first + ":" + second
  4503. will match ``"1:1"``, but not ``"1:2"``. Because this
  4504. matches a previous literal, will also match the leading
  4505. ``"1:1"`` in ``"1:10"``. If this is not desired, use
  4506. :class:`matchPreviousExpr`. Do *not* use with packrat parsing
  4507. enabled.
  4508. """
  4509. rep = Forward()
  4510. def copyTokenToRepeater(s, l, t):
  4511. if t:
  4512. if len(t) == 1:
  4513. rep << t[0]
  4514. else:
  4515. # flatten t tokens
  4516. tflat = _flatten(t.asList())
  4517. rep << And(Literal(tt) for tt in tflat)
  4518. else:
  4519. rep << Empty()
  4520. expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
  4521. rep.setName('(prev) ' + _ustr(expr))
  4522. return rep
  4523. def matchPreviousExpr(expr):
  4524. """Helper to define an expression that is indirectly defined from
  4525. the tokens matched in a previous expression, that is, it looks for
  4526. a 'repeat' of a previous expression. For example::
  4527. first = Word(nums)
  4528. second = matchPreviousExpr(first)
  4529. matchExpr = first + ":" + second
  4530. will match ``"1:1"``, but not ``"1:2"``. Because this
  4531. matches by expressions, will *not* match the leading ``"1:1"``
  4532. in ``"1:10"``; the expressions are evaluated first, and then
  4533. compared, so ``"1"`` is compared with ``"10"``. Do *not* use
  4534. with packrat parsing enabled.
  4535. """
  4536. rep = Forward()
  4537. e2 = expr.copy()
  4538. rep <<= e2
  4539. def copyTokenToRepeater(s, l, t):
  4540. matchTokens = _flatten(t.asList())
  4541. def mustMatchTheseTokens(s, l, t):
  4542. theseTokens = _flatten(t.asList())
  4543. if theseTokens != matchTokens:
  4544. raise ParseException('', 0, '')
  4545. rep.setParseAction(mustMatchTheseTokens, callDuringTry=True)
  4546. expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
  4547. rep.setName('(prev) ' + _ustr(expr))
  4548. return rep
  4549. def _escapeRegexRangeChars(s):
  4550. # ~ escape these chars: ^-[]
  4551. for c in r"\^-[]":
  4552. s = s.replace(c, _bslash + c)
  4553. s = s.replace("\n", r"\n")
  4554. s = s.replace("\t", r"\t")
  4555. return _ustr(s)
  4556. def oneOf(strs, caseless=False, useRegex=True, asKeyword=False):
  4557. """Helper to quickly define a set of alternative Literals, and makes
  4558. sure to do longest-first testing when there is a conflict,
  4559. regardless of the input order, but returns
  4560. a :class:`MatchFirst` for best performance.
  4561. Parameters:
  4562. - strs - a string of space-delimited literals, or a collection of
  4563. string literals
  4564. - caseless - (default= ``False``) - treat all literals as
  4565. caseless
  4566. - useRegex - (default= ``True``) - as an optimization, will
  4567. generate a Regex object; otherwise, will generate
  4568. a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if
  4569. creating a :class:`Regex` raises an exception)
  4570. - asKeyword - (default=``False``) - enforce Keyword-style matching on the
  4571. generated expressions
  4572. Example::
  4573. comp_oper = oneOf("< = > <= >= !=")
  4574. var = Word(alphas)
  4575. number = Word(nums)
  4576. term = var | number
  4577. comparison_expr = term + comp_oper + term
  4578. print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12"))
  4579. prints::
  4580. [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
  4581. """
  4582. if isinstance(caseless, basestring):
  4583. warnings.warn("More than one string argument passed to oneOf, pass "
  4584. "choices as a list or space-delimited string", stacklevel=2)
  4585. if caseless:
  4586. isequal = (lambda a, b: a.upper() == b.upper())
  4587. masks = (lambda a, b: b.upper().startswith(a.upper()))
  4588. parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral
  4589. else:
  4590. isequal = (lambda a, b: a == b)
  4591. masks = (lambda a, b: b.startswith(a))
  4592. parseElementClass = Keyword if asKeyword else Literal
  4593. symbols = []
  4594. if isinstance(strs, basestring):
  4595. symbols = strs.split()
  4596. elif isinstance(strs, Iterable):
  4597. symbols = list(strs)
  4598. else:
  4599. warnings.warn("Invalid argument to oneOf, expected string or iterable",
  4600. SyntaxWarning, stacklevel=2)
  4601. if not symbols:
  4602. return NoMatch()
  4603. if not asKeyword:
  4604. # if not producing keywords, need to reorder to take care to avoid masking
  4605. # longer choices with shorter ones
  4606. i = 0
  4607. while i < len(symbols) - 1:
  4608. cur = symbols[i]
  4609. for j, other in enumerate(symbols[i + 1:]):
  4610. if isequal(other, cur):
  4611. del symbols[i + j + 1]
  4612. break
  4613. elif masks(cur, other):
  4614. del symbols[i + j + 1]
  4615. symbols.insert(i, other)
  4616. break
  4617. else:
  4618. i += 1
  4619. if not (caseless or asKeyword) and useRegex:
  4620. # ~ print (strs, "->", "|".join([_escapeRegexChars(sym) for sym in symbols]))
  4621. try:
  4622. if len(symbols) == len("".join(symbols)):
  4623. return Regex("[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols)).setName(' | '.join(symbols))
  4624. else:
  4625. return Regex("|".join(re.escape(sym) for sym in symbols)).setName(' | '.join(symbols))
  4626. except Exception:
  4627. warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
  4628. SyntaxWarning, stacklevel=2)
  4629. # last resort, just use MatchFirst
  4630. return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols))
  4631. def dictOf(key, value):
  4632. """Helper to easily and clearly define a dictionary by specifying
  4633. the respective patterns for the key and value. Takes care of
  4634. defining the :class:`Dict`, :class:`ZeroOrMore`, and
  4635. :class:`Group` tokens in the proper order. The key pattern
  4636. can include delimiting markers or punctuation, as long as they are
  4637. suppressed, thereby leaving the significant key text. The value
  4638. pattern can include named results, so that the :class:`Dict` results
  4639. can include named token fields.
  4640. Example::
  4641. text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
  4642. attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
  4643. print(OneOrMore(attr_expr).parseString(text).dump())
  4644. attr_label = label
  4645. attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
  4646. # similar to Dict, but simpler call format
  4647. result = dictOf(attr_label, attr_value).parseString(text)
  4648. print(result.dump())
  4649. print(result['shape'])
  4650. print(result.shape) # object attribute access works too
  4651. print(result.asDict())
  4652. prints::
  4653. [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
  4654. - color: light blue
  4655. - posn: upper left
  4656. - shape: SQUARE
  4657. - texture: burlap
  4658. SQUARE
  4659. SQUARE
  4660. {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
  4661. """
  4662. return Dict(OneOrMore(Group(key + value)))
  4663. def originalTextFor(expr, asString=True):
  4664. """Helper to return the original, untokenized text for a given
  4665. expression. Useful to restore the parsed fields of an HTML start
  4666. tag into the raw tag text itself, or to revert separate tokens with
  4667. intervening whitespace back to the original matching input text. By
  4668. default, returns astring containing the original parsed text.
  4669. If the optional ``asString`` argument is passed as
  4670. ``False``, then the return value is
  4671. a :class:`ParseResults` containing any results names that
  4672. were originally matched, and a single token containing the original
  4673. matched text from the input string. So if the expression passed to
  4674. :class:`originalTextFor` contains expressions with defined
  4675. results names, you must set ``asString`` to ``False`` if you
  4676. want to preserve those results name values.
  4677. Example::
  4678. src = "this is test <b> bold <i>text</i> </b> normal text "
  4679. for tag in ("b", "i"):
  4680. opener, closer = makeHTMLTags(tag)
  4681. patt = originalTextFor(opener + SkipTo(closer) + closer)
  4682. print(patt.searchString(src)[0])
  4683. prints::
  4684. ['<b> bold <i>text</i> </b>']
  4685. ['<i>text</i>']
  4686. """
  4687. locMarker = Empty().setParseAction(lambda s, loc, t: loc)
  4688. endlocMarker = locMarker.copy()
  4689. endlocMarker.callPreparse = False
  4690. matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
  4691. if asString:
  4692. extractText = lambda s, l, t: s[t._original_start: t._original_end]
  4693. else:
  4694. def extractText(s, l, t):
  4695. t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
  4696. matchExpr.setParseAction(extractText)
  4697. matchExpr.ignoreExprs = expr.ignoreExprs
  4698. return matchExpr
  4699. def ungroup(expr):
  4700. """Helper to undo pyparsing's default grouping of And expressions,
  4701. even if all but one are non-empty.
  4702. """
  4703. return TokenConverter(expr).addParseAction(lambda t: t[0])
  4704. def locatedExpr(expr):
  4705. """Helper to decorate a returned token with its starting and ending
  4706. locations in the input string.
  4707. This helper adds the following results names:
  4708. - locn_start = location where matched expression begins
  4709. - locn_end = location where matched expression ends
  4710. - value = the actual parsed results
  4711. Be careful if the input text contains ``<TAB>`` characters, you
  4712. may want to call :class:`ParserElement.parseWithTabs`
  4713. Example::
  4714. wd = Word(alphas)
  4715. for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
  4716. print(match)
  4717. prints::
  4718. [[0, 'ljsdf', 5]]
  4719. [[8, 'lksdjjf', 15]]
  4720. [[18, 'lkkjj', 23]]
  4721. """
  4722. locator = Empty().setParseAction(lambda s, l, t: l)
  4723. return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
  4724. # convenience constants for positional expressions
  4725. empty = Empty().setName("empty")
  4726. lineStart = LineStart().setName("lineStart")
  4727. lineEnd = LineEnd().setName("lineEnd")
  4728. stringStart = StringStart().setName("stringStart")
  4729. stringEnd = StringEnd().setName("stringEnd")
  4730. _escapedPunc = Word(_bslash, r"\[]-*.$+^?()~ ", exact=2).setParseAction(lambda s, l, t: t[0][1])
  4731. _escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s, l, t: unichr(int(t[0].lstrip(r'\0x'), 16)))
  4732. _escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s, l, t: unichr(int(t[0][1:], 8)))
  4733. _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r'\]', exact=1)
  4734. _charRange = Group(_singleChar + Suppress("-") + _singleChar)
  4735. _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group(OneOrMore(_charRange | _singleChar)).setResultsName("body") + "]"
  4736. def srange(s):
  4737. r"""Helper to easily define string ranges for use in Word
  4738. construction. Borrows syntax from regexp '[]' string range
  4739. definitions::
  4740. srange("[0-9]") -> "0123456789"
  4741. srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
  4742. srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
  4743. The input string must be enclosed in []'s, and the returned string
  4744. is the expanded character set joined into a single string. The
  4745. values enclosed in the []'s may be:
  4746. - a single character
  4747. - an escaped character with a leading backslash (such as ``\-``
  4748. or ``\]``)
  4749. - an escaped hex character with a leading ``'\x'``
  4750. (``\x21``, which is a ``'!'`` character) (``\0x##``
  4751. is also supported for backwards compatibility)
  4752. - an escaped octal character with a leading ``'\0'``
  4753. (``\041``, which is a ``'!'`` character)
  4754. - a range of any of the above, separated by a dash (``'a-z'``,
  4755. etc.)
  4756. - any combination of the above (``'aeiouy'``,
  4757. ``'a-zA-Z0-9_$'``, etc.)
  4758. """
  4759. _expanded = lambda p: p if not isinstance(p, ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]), ord(p[1]) + 1))
  4760. try:
  4761. return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
  4762. except Exception:
  4763. return ""
  4764. def matchOnlyAtCol(n):
  4765. """Helper method for defining parse actions that require matching at
  4766. a specific column in the input text.
  4767. """
  4768. def verifyCol(strg, locn, toks):
  4769. if col(locn, strg) != n:
  4770. raise ParseException(strg, locn, "matched token not at column %d" % n)
  4771. return verifyCol
  4772. def replaceWith(replStr):
  4773. """Helper method for common parse actions that simply return
  4774. a literal value. Especially useful when used with
  4775. :class:`transformString<ParserElement.transformString>` ().
  4776. Example::
  4777. num = Word(nums).setParseAction(lambda toks: int(toks[0]))
  4778. na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
  4779. term = na | num
  4780. OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
  4781. """
  4782. return lambda s, l, t: [replStr]
  4783. def removeQuotes(s, l, t):
  4784. """Helper parse action for removing quotation marks from parsed
  4785. quoted strings.
  4786. Example::
  4787. # by default, quotation marks are included in parsed results
  4788. quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
  4789. # use removeQuotes to strip quotation marks from parsed results
  4790. quotedString.setParseAction(removeQuotes)
  4791. quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
  4792. """
  4793. return t[0][1:-1]
  4794. def tokenMap(func, *args):
  4795. """Helper to define a parse action by mapping a function to all
  4796. elements of a ParseResults list. If any additional args are passed,
  4797. they are forwarded to the given function as additional arguments
  4798. after the token, as in
  4799. ``hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))``,
  4800. which will convert the parsed data to an integer using base 16.
  4801. Example (compare the last to example in :class:`ParserElement.transformString`::
  4802. hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
  4803. hex_ints.runTests('''
  4804. 00 11 22 aa FF 0a 0d 1a
  4805. ''')
  4806. upperword = Word(alphas).setParseAction(tokenMap(str.upper))
  4807. OneOrMore(upperword).runTests('''
  4808. my kingdom for a horse
  4809. ''')
  4810. wd = Word(alphas).setParseAction(tokenMap(str.title))
  4811. OneOrMore(wd).setParseAction(' '.join).runTests('''
  4812. now is the winter of our discontent made glorious summer by this sun of york
  4813. ''')
  4814. prints::
  4815. 00 11 22 aa FF 0a 0d 1a
  4816. [0, 17, 34, 170, 255, 10, 13, 26]
  4817. my kingdom for a horse
  4818. ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
  4819. now is the winter of our discontent made glorious summer by this sun of york
  4820. ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
  4821. """
  4822. def pa(s, l, t):
  4823. return [func(tokn, *args) for tokn in t]
  4824. try:
  4825. func_name = getattr(func, '__name__',
  4826. getattr(func, '__class__').__name__)
  4827. except Exception:
  4828. func_name = str(func)
  4829. pa.__name__ = func_name
  4830. return pa
  4831. upcaseTokens = tokenMap(lambda t: _ustr(t).upper())
  4832. """(Deprecated) Helper parse action to convert tokens to upper case.
  4833. Deprecated in favor of :class:`pyparsing_common.upcaseTokens`"""
  4834. downcaseTokens = tokenMap(lambda t: _ustr(t).lower())
  4835. """(Deprecated) Helper parse action to convert tokens to lower case.
  4836. Deprecated in favor of :class:`pyparsing_common.downcaseTokens`"""
  4837. def _makeTags(tagStr, xml,
  4838. suppress_LT=Suppress("<"),
  4839. suppress_GT=Suppress(">")):
  4840. """Internal helper to construct opening and closing tag expressions, given a tag name"""
  4841. if isinstance(tagStr, basestring):
  4842. resname = tagStr
  4843. tagStr = Keyword(tagStr, caseless=not xml)
  4844. else:
  4845. resname = tagStr.name
  4846. tagAttrName = Word(alphas, alphanums + "_-:")
  4847. if xml:
  4848. tagAttrValue = dblQuotedString.copy().setParseAction(removeQuotes)
  4849. openTag = (suppress_LT
  4850. + tagStr("tag")
  4851. + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue)))
  4852. + Optional("/", default=[False])("empty").setParseAction(lambda s, l, t: t[0] == '/')
  4853. + suppress_GT)
  4854. else:
  4855. tagAttrValue = quotedString.copy().setParseAction(removeQuotes) | Word(printables, excludeChars=">")
  4856. openTag = (suppress_LT
  4857. + tagStr("tag")
  4858. + Dict(ZeroOrMore(Group(tagAttrName.setParseAction(downcaseTokens)
  4859. + Optional(Suppress("=") + tagAttrValue))))
  4860. + Optional("/", default=[False])("empty").setParseAction(lambda s, l, t: t[0] == '/')
  4861. + suppress_GT)
  4862. closeTag = Combine(_L("</") + tagStr + ">", adjacent=False)
  4863. openTag.setName("<%s>" % resname)
  4864. # add start<tagname> results name in parse action now that ungrouped names are not reported at two levels
  4865. openTag.addParseAction(lambda t: t.__setitem__("start" + "".join(resname.replace(":", " ").title().split()), t.copy()))
  4866. closeTag = closeTag("end" + "".join(resname.replace(":", " ").title().split())).setName("</%s>" % resname)
  4867. openTag.tag = resname
  4868. closeTag.tag = resname
  4869. openTag.tag_body = SkipTo(closeTag())
  4870. return openTag, closeTag
  4871. def makeHTMLTags(tagStr):
  4872. """Helper to construct opening and closing tag expressions for HTML,
  4873. given a tag name. Matches tags in either upper or lower case,
  4874. attributes with namespaces and with quoted or unquoted values.
  4875. Example::
  4876. text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
  4877. # makeHTMLTags returns pyparsing expressions for the opening and
  4878. # closing tags as a 2-tuple
  4879. a, a_end = makeHTMLTags("A")
  4880. link_expr = a + SkipTo(a_end)("link_text") + a_end
  4881. for link in link_expr.searchString(text):
  4882. # attributes in the <A> tag (like "href" shown here) are
  4883. # also accessible as named results
  4884. print(link.link_text, '->', link.href)
  4885. prints::
  4886. pyparsing -> https://github.com/pyparsing/pyparsing/wiki
  4887. """
  4888. return _makeTags(tagStr, False)
  4889. def makeXMLTags(tagStr):
  4890. """Helper to construct opening and closing tag expressions for XML,
  4891. given a tag name. Matches tags only in the given upper/lower case.
  4892. Example: similar to :class:`makeHTMLTags`
  4893. """
  4894. return _makeTags(tagStr, True)
  4895. def withAttribute(*args, **attrDict):
  4896. """Helper to create a validating parse action to be used with start
  4897. tags created with :class:`makeXMLTags` or
  4898. :class:`makeHTMLTags`. Use ``withAttribute`` to qualify
  4899. a starting tag with a required attribute value, to avoid false
  4900. matches on common tags such as ``<TD>`` or ``<DIV>``.
  4901. Call ``withAttribute`` with a series of attribute names and
  4902. values. Specify the list of filter attributes names and values as:
  4903. - keyword arguments, as in ``(align="right")``, or
  4904. - as an explicit dict with ``**`` operator, when an attribute
  4905. name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
  4906. - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
  4907. For attribute names with a namespace prefix, you must use the second
  4908. form. Attribute names are matched insensitive to upper/lower case.
  4909. If just testing for ``class`` (with or without a namespace), use
  4910. :class:`withClass`.
  4911. To verify that the attribute exists, but without specifying a value,
  4912. pass ``withAttribute.ANY_VALUE`` as the value.
  4913. Example::
  4914. html = '''
  4915. <div>
  4916. Some text
  4917. <div type="grid">1 4 0 1 0</div>
  4918. <div type="graph">1,3 2,3 1,1</div>
  4919. <div>this has no type</div>
  4920. </div>
  4921. '''
  4922. div,div_end = makeHTMLTags("div")
  4923. # only match div tag having a type attribute with value "grid"
  4924. div_grid = div().setParseAction(withAttribute(type="grid"))
  4925. grid_expr = div_grid + SkipTo(div | div_end)("body")
  4926. for grid_header in grid_expr.searchString(html):
  4927. print(grid_header.body)
  4928. # construct a match with any div tag having a type attribute, regardless of the value
  4929. div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
  4930. div_expr = div_any_type + SkipTo(div | div_end)("body")
  4931. for div_header in div_expr.searchString(html):
  4932. print(div_header.body)
  4933. prints::
  4934. 1 4 0 1 0
  4935. 1 4 0 1 0
  4936. 1,3 2,3 1,1
  4937. """
  4938. if args:
  4939. attrs = args[:]
  4940. else:
  4941. attrs = attrDict.items()
  4942. attrs = [(k, v) for k, v in attrs]
  4943. def pa(s, l, tokens):
  4944. for attrName, attrValue in attrs:
  4945. if attrName not in tokens:
  4946. raise ParseException(s, l, "no matching attribute " + attrName)
  4947. if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
  4948. raise ParseException(s, l, "attribute '%s' has value '%s', must be '%s'" %
  4949. (attrName, tokens[attrName], attrValue))
  4950. return pa
  4951. withAttribute.ANY_VALUE = object()
  4952. def withClass(classname, namespace=''):
  4953. """Simplified version of :class:`withAttribute` when
  4954. matching on a div class - made difficult because ``class`` is
  4955. a reserved word in Python.
  4956. Example::
  4957. html = '''
  4958. <div>
  4959. Some text
  4960. <div class="grid">1 4 0 1 0</div>
  4961. <div class="graph">1,3 2,3 1,1</div>
  4962. <div>this &lt;div&gt; has no class</div>
  4963. </div>
  4964. '''
  4965. div,div_end = makeHTMLTags("div")
  4966. div_grid = div().setParseAction(withClass("grid"))
  4967. grid_expr = div_grid + SkipTo(div | div_end)("body")
  4968. for grid_header in grid_expr.searchString(html):
  4969. print(grid_header.body)
  4970. div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
  4971. div_expr = div_any_type + SkipTo(div | div_end)("body")
  4972. for div_header in div_expr.searchString(html):
  4973. print(div_header.body)
  4974. prints::
  4975. 1 4 0 1 0
  4976. 1 4 0 1 0
  4977. 1,3 2,3 1,1
  4978. """
  4979. classattr = "%s:class" % namespace if namespace else "class"
  4980. return withAttribute(**{classattr: classname})
  4981. opAssoc = SimpleNamespace()
  4982. opAssoc.LEFT = object()
  4983. opAssoc.RIGHT = object()
  4984. def infixNotation(baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')')):
  4985. """Helper method for constructing grammars of expressions made up of
  4986. operators working in a precedence hierarchy. Operators may be unary
  4987. or binary, left- or right-associative. Parse actions can also be
  4988. attached to operator expressions. The generated parser will also
  4989. recognize the use of parentheses to override operator precedences
  4990. (see example below).
  4991. Note: if you define a deep operator list, you may see performance
  4992. issues when using infixNotation. See
  4993. :class:`ParserElement.enablePackrat` for a mechanism to potentially
  4994. improve your parser performance.
  4995. Parameters:
  4996. - baseExpr - expression representing the most basic element for the
  4997. nested
  4998. - opList - list of tuples, one for each operator precedence level
  4999. in the expression grammar; each tuple is of the form ``(opExpr,
  5000. numTerms, rightLeftAssoc, parseAction)``, where:
  5001. - opExpr is the pyparsing expression for the operator; may also
  5002. be a string, which will be converted to a Literal; if numTerms
  5003. is 3, opExpr is a tuple of two expressions, for the two
  5004. operators separating the 3 terms
  5005. - numTerms is the number of terms for this operator (must be 1,
  5006. 2, or 3)
  5007. - rightLeftAssoc is the indicator whether the operator is right
  5008. or left associative, using the pyparsing-defined constants
  5009. ``opAssoc.RIGHT`` and ``opAssoc.LEFT``.
  5010. - parseAction is the parse action to be associated with
  5011. expressions matching this operator expression (the parse action
  5012. tuple member may be omitted); if the parse action is passed
  5013. a tuple or list of functions, this is equivalent to calling
  5014. ``setParseAction(*fn)``
  5015. (:class:`ParserElement.setParseAction`)
  5016. - lpar - expression for matching left-parentheses
  5017. (default= ``Suppress('(')``)
  5018. - rpar - expression for matching right-parentheses
  5019. (default= ``Suppress(')')``)
  5020. Example::
  5021. # simple example of four-function arithmetic with ints and
  5022. # variable names
  5023. integer = pyparsing_common.signed_integer
  5024. varname = pyparsing_common.identifier
  5025. arith_expr = infixNotation(integer | varname,
  5026. [
  5027. ('-', 1, opAssoc.RIGHT),
  5028. (oneOf('* /'), 2, opAssoc.LEFT),
  5029. (oneOf('+ -'), 2, opAssoc.LEFT),
  5030. ])
  5031. arith_expr.runTests('''
  5032. 5+3*6
  5033. (5+3)*6
  5034. -2--11
  5035. ''', fullDump=False)
  5036. prints::
  5037. 5+3*6
  5038. [[5, '+', [3, '*', 6]]]
  5039. (5+3)*6
  5040. [[[5, '+', 3], '*', 6]]
  5041. -2--11
  5042. [[['-', 2], '-', ['-', 11]]]
  5043. """
  5044. # captive version of FollowedBy that does not do parse actions or capture results names
  5045. class _FB(FollowedBy):
  5046. def parseImpl(self, instring, loc, doActions=True):
  5047. self.expr.tryParse(instring, loc)
  5048. return loc, []
  5049. ret = Forward()
  5050. lastExpr = baseExpr | (lpar + ret + rpar)
  5051. for i, operDef in enumerate(opList):
  5052. opExpr, arity, rightLeftAssoc, pa = (operDef + (None, ))[:4]
  5053. termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr
  5054. if arity == 3:
  5055. if opExpr is None or len(opExpr) != 2:
  5056. raise ValueError(
  5057. "if numterms=3, opExpr must be a tuple or list of two expressions")
  5058. opExpr1, opExpr2 = opExpr
  5059. thisExpr = Forward().setName(termName)
  5060. if rightLeftAssoc == opAssoc.LEFT:
  5061. if arity == 1:
  5062. matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + OneOrMore(opExpr))
  5063. elif arity == 2:
  5064. if opExpr is not None:
  5065. matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(lastExpr + OneOrMore(opExpr + lastExpr))
  5066. else:
  5067. matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr + OneOrMore(lastExpr))
  5068. elif arity == 3:
  5069. matchExpr = (_FB(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr)
  5070. + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr)))
  5071. else:
  5072. raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
  5073. elif rightLeftAssoc == opAssoc.RIGHT:
  5074. if arity == 1:
  5075. # try to avoid LR with this extra test
  5076. if not isinstance(opExpr, Optional):
  5077. opExpr = Optional(opExpr)
  5078. matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)
  5079. elif arity == 2:
  5080. if opExpr is not None:
  5081. matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(lastExpr + OneOrMore(opExpr + thisExpr))
  5082. else:
  5083. matchExpr = _FB(lastExpr + thisExpr) + Group(lastExpr + OneOrMore(thisExpr))
  5084. elif arity == 3:
  5085. matchExpr = (_FB(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)
  5086. + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr))
  5087. else:
  5088. raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
  5089. else:
  5090. raise ValueError("operator must indicate right or left associativity")
  5091. if pa:
  5092. if isinstance(pa, (tuple, list)):
  5093. matchExpr.setParseAction(*pa)
  5094. else:
  5095. matchExpr.setParseAction(pa)
  5096. thisExpr <<= (matchExpr.setName(termName) | lastExpr)
  5097. lastExpr = thisExpr
  5098. ret <<= lastExpr
  5099. return ret
  5100. operatorPrecedence = infixNotation
  5101. """(Deprecated) Former name of :class:`infixNotation`, will be
  5102. dropped in a future release."""
  5103. dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').setName("string enclosed in double quotes")
  5104. sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").setName("string enclosed in single quotes")
  5105. quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"'
  5106. | Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").setName("quotedString using single or double quotes")
  5107. unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal")
  5108. def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
  5109. """Helper method for defining nested lists enclosed in opening and
  5110. closing delimiters ("(" and ")" are the default).
  5111. Parameters:
  5112. - opener - opening character for a nested list
  5113. (default= ``"("``); can also be a pyparsing expression
  5114. - closer - closing character for a nested list
  5115. (default= ``")"``); can also be a pyparsing expression
  5116. - content - expression for items within the nested lists
  5117. (default= ``None``)
  5118. - ignoreExpr - expression for ignoring opening and closing
  5119. delimiters (default= :class:`quotedString`)
  5120. If an expression is not provided for the content argument, the
  5121. nested expression will capture all whitespace-delimited content
  5122. between delimiters as a list of separate values.
  5123. Use the ``ignoreExpr`` argument to define expressions that may
  5124. contain opening or closing characters that should not be treated as
  5125. opening or closing characters for nesting, such as quotedString or
  5126. a comment expression. Specify multiple expressions using an
  5127. :class:`Or` or :class:`MatchFirst`. The default is
  5128. :class:`quotedString`, but if no expressions are to be ignored, then
  5129. pass ``None`` for this argument.
  5130. Example::
  5131. data_type = oneOf("void int short long char float double")
  5132. decl_data_type = Combine(data_type + Optional(Word('*')))
  5133. ident = Word(alphas+'_', alphanums+'_')
  5134. number = pyparsing_common.number
  5135. arg = Group(decl_data_type + ident)
  5136. LPAR, RPAR = map(Suppress, "()")
  5137. code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment))
  5138. c_function = (decl_data_type("type")
  5139. + ident("name")
  5140. + LPAR + Optional(delimitedList(arg), [])("args") + RPAR
  5141. + code_body("body"))
  5142. c_function.ignore(cStyleComment)
  5143. source_code = '''
  5144. int is_odd(int x) {
  5145. return (x%2);
  5146. }
  5147. int dec_to_hex(char hchar) {
  5148. if (hchar >= '0' && hchar <= '9') {
  5149. return (ord(hchar)-ord('0'));
  5150. } else {
  5151. return (10+ord(hchar)-ord('A'));
  5152. }
  5153. }
  5154. '''
  5155. for func in c_function.searchString(source_code):
  5156. print("%(name)s (%(type)s) args: %(args)s" % func)
  5157. prints::
  5158. is_odd (int) args: [['int', 'x']]
  5159. dec_to_hex (int) args: [['char', 'hchar']]
  5160. """
  5161. if opener == closer:
  5162. raise ValueError("opening and closing strings cannot be the same")
  5163. if content is None:
  5164. if isinstance(opener, basestring) and isinstance(closer, basestring):
  5165. if len(opener) == 1 and len(closer) == 1:
  5166. if ignoreExpr is not None:
  5167. content = (Combine(OneOrMore(~ignoreExpr
  5168. + CharsNotIn(opener
  5169. + closer
  5170. + ParserElement.DEFAULT_WHITE_CHARS, exact=1)
  5171. )
  5172. ).setParseAction(lambda t: t[0].strip()))
  5173. else:
  5174. content = (empty.copy() + CharsNotIn(opener
  5175. + closer
  5176. + ParserElement.DEFAULT_WHITE_CHARS
  5177. ).setParseAction(lambda t: t[0].strip()))
  5178. else:
  5179. if ignoreExpr is not None:
  5180. content = (Combine(OneOrMore(~ignoreExpr
  5181. + ~Literal(opener)
  5182. + ~Literal(closer)
  5183. + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1))
  5184. ).setParseAction(lambda t: t[0].strip()))
  5185. else:
  5186. content = (Combine(OneOrMore(~Literal(opener)
  5187. + ~Literal(closer)
  5188. + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1))
  5189. ).setParseAction(lambda t: t[0].strip()))
  5190. else:
  5191. raise ValueError("opening and closing arguments must be strings if no content expression is given")
  5192. ret = Forward()
  5193. if ignoreExpr is not None:
  5194. ret <<= Group(Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer))
  5195. else:
  5196. ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))
  5197. ret.setName('nested %s%s expression' % (opener, closer))
  5198. return ret
  5199. def indentedBlock(blockStatementExpr, indentStack, indent=True):
  5200. """Helper method for defining space-delimited indentation blocks,
  5201. such as those used to define block statements in Python source code.
  5202. Parameters:
  5203. - blockStatementExpr - expression defining syntax of statement that
  5204. is repeated within the indented block
  5205. - indentStack - list created by caller to manage indentation stack
  5206. (multiple statementWithIndentedBlock expressions within a single
  5207. grammar should share a common indentStack)
  5208. - indent - boolean indicating whether block must be indented beyond
  5209. the current level; set to False for block of left-most
  5210. statements (default= ``True``)
  5211. A valid block must contain at least one ``blockStatement``.
  5212. Example::
  5213. data = '''
  5214. def A(z):
  5215. A1
  5216. B = 100
  5217. G = A2
  5218. A2
  5219. A3
  5220. B
  5221. def BB(a,b,c):
  5222. BB1
  5223. def BBA():
  5224. bba1
  5225. bba2
  5226. bba3
  5227. C
  5228. D
  5229. def spam(x,y):
  5230. def eggs(z):
  5231. pass
  5232. '''
  5233. indentStack = [1]
  5234. stmt = Forward()
  5235. identifier = Word(alphas, alphanums)
  5236. funcDecl = ("def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":")
  5237. func_body = indentedBlock(stmt, indentStack)
  5238. funcDef = Group(funcDecl + func_body)
  5239. rvalue = Forward()
  5240. funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
  5241. rvalue << (funcCall | identifier | Word(nums))
  5242. assignment = Group(identifier + "=" + rvalue)
  5243. stmt << (funcDef | assignment | identifier)
  5244. module_body = OneOrMore(stmt)
  5245. parseTree = module_body.parseString(data)
  5246. parseTree.pprint()
  5247. prints::
  5248. [['def',
  5249. 'A',
  5250. ['(', 'z', ')'],
  5251. ':',
  5252. [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
  5253. 'B',
  5254. ['def',
  5255. 'BB',
  5256. ['(', 'a', 'b', 'c', ')'],
  5257. ':',
  5258. [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
  5259. 'C',
  5260. 'D',
  5261. ['def',
  5262. 'spam',
  5263. ['(', 'x', 'y', ')'],
  5264. ':',
  5265. [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
  5266. """
  5267. backup_stack = indentStack[:]
  5268. def reset_stack():
  5269. indentStack[:] = backup_stack
  5270. def checkPeerIndent(s, l, t):
  5271. if l >= len(s): return
  5272. curCol = col(l, s)
  5273. if curCol != indentStack[-1]:
  5274. if curCol > indentStack[-1]:
  5275. raise ParseException(s, l, "illegal nesting")
  5276. raise ParseException(s, l, "not a peer entry")
  5277. def checkSubIndent(s, l, t):
  5278. curCol = col(l, s)
  5279. if curCol > indentStack[-1]:
  5280. indentStack.append(curCol)
  5281. else:
  5282. raise ParseException(s, l, "not a subentry")
  5283. def checkUnindent(s, l, t):
  5284. if l >= len(s): return
  5285. curCol = col(l, s)
  5286. if not(indentStack and curCol in indentStack):
  5287. raise ParseException(s, l, "not an unindent")
  5288. if curCol < indentStack[-1]:
  5289. indentStack.pop()
  5290. NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress(), stopOn=StringEnd())
  5291. INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
  5292. PEER = Empty().setParseAction(checkPeerIndent).setName('')
  5293. UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
  5294. if indent:
  5295. smExpr = Group(Optional(NL)
  5296. + INDENT
  5297. + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd())
  5298. + UNDENT)
  5299. else:
  5300. smExpr = Group(Optional(NL)
  5301. + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd())
  5302. + UNDENT)
  5303. smExpr.setFailAction(lambda a, b, c, d: reset_stack())
  5304. blockStatementExpr.ignore(_bslash + LineEnd())
  5305. return smExpr.setName('indented block')
  5306. alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
  5307. punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
  5308. anyOpenTag, anyCloseTag = makeHTMLTags(Word(alphas, alphanums + "_:").setName('any tag'))
  5309. _htmlEntityMap = dict(zip("gt lt amp nbsp quot apos".split(), '><& "\''))
  5310. commonHTMLEntity = Regex('&(?P<entity>' + '|'.join(_htmlEntityMap.keys()) +");").setName("common HTML entity")
  5311. def replaceHTMLEntity(t):
  5312. """Helper parser action to replace common HTML entities with their special characters"""
  5313. return _htmlEntityMap.get(t.entity)
  5314. # it's easy to get these comment structures wrong - they're very common, so may as well make them available
  5315. cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment")
  5316. "Comment of the form ``/* ... */``"
  5317. htmlComment = Regex(r"<!--[\s\S]*?-->").setName("HTML comment")
  5318. "Comment of the form ``<!-- ... -->``"
  5319. restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line")
  5320. dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment")
  5321. "Comment of the form ``// ... (to end of line)``"
  5322. cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/' | dblSlashComment).setName("C++ style comment")
  5323. "Comment of either form :class:`cStyleComment` or :class:`dblSlashComment`"
  5324. javaStyleComment = cppStyleComment
  5325. "Same as :class:`cppStyleComment`"
  5326. pythonStyleComment = Regex(r"#.*").setName("Python style comment")
  5327. "Comment of the form ``# ... (to end of line)``"
  5328. _commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',')
  5329. + Optional(Word(" \t")
  5330. + ~Literal(",") + ~LineEnd()))).streamline().setName("commaItem")
  5331. commaSeparatedList = delimitedList(Optional(quotedString.copy() | _commasepitem, default="")).setName("commaSeparatedList")
  5332. """(Deprecated) Predefined expression of 1 or more printable words or
  5333. quoted strings, separated by commas.
  5334. This expression is deprecated in favor of :class:`pyparsing_common.comma_separated_list`.
  5335. """
  5336. # some other useful expressions - using lower-case class name since we are really using this as a namespace
  5337. class pyparsing_common:
  5338. """Here are some common low-level expressions that may be useful in
  5339. jump-starting parser development:
  5340. - numeric forms (:class:`integers<integer>`, :class:`reals<real>`,
  5341. :class:`scientific notation<sci_real>`)
  5342. - common :class:`programming identifiers<identifier>`
  5343. - network addresses (:class:`MAC<mac_address>`,
  5344. :class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)
  5345. - ISO8601 :class:`dates<iso8601_date>` and
  5346. :class:`datetime<iso8601_datetime>`
  5347. - :class:`UUID<uuid>`
  5348. - :class:`comma-separated list<comma_separated_list>`
  5349. Parse actions:
  5350. - :class:`convertToInteger`
  5351. - :class:`convertToFloat`
  5352. - :class:`convertToDate`
  5353. - :class:`convertToDatetime`
  5354. - :class:`stripHTMLTags`
  5355. - :class:`upcaseTokens`
  5356. - :class:`downcaseTokens`
  5357. Example::
  5358. pyparsing_common.number.runTests('''
  5359. # any int or real number, returned as the appropriate type
  5360. 100
  5361. -100
  5362. +100
  5363. 3.14159
  5364. 6.02e23
  5365. 1e-12
  5366. ''')
  5367. pyparsing_common.fnumber.runTests('''
  5368. # any int or real number, returned as float
  5369. 100
  5370. -100
  5371. +100
  5372. 3.14159
  5373. 6.02e23
  5374. 1e-12
  5375. ''')
  5376. pyparsing_common.hex_integer.runTests('''
  5377. # hex numbers
  5378. 100
  5379. FF
  5380. ''')
  5381. pyparsing_common.fraction.runTests('''
  5382. # fractions
  5383. 1/2
  5384. -3/4
  5385. ''')
  5386. pyparsing_common.mixed_integer.runTests('''
  5387. # mixed fractions
  5388. 1
  5389. 1/2
  5390. -3/4
  5391. 1-3/4
  5392. ''')
  5393. import uuid
  5394. pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
  5395. pyparsing_common.uuid.runTests('''
  5396. # uuid
  5397. 12345678-1234-5678-1234-567812345678
  5398. ''')
  5399. prints::
  5400. # any int or real number, returned as the appropriate type
  5401. 100
  5402. [100]
  5403. -100
  5404. [-100]
  5405. +100
  5406. [100]
  5407. 3.14159
  5408. [3.14159]
  5409. 6.02e23
  5410. [6.02e+23]
  5411. 1e-12
  5412. [1e-12]
  5413. # any int or real number, returned as float
  5414. 100
  5415. [100.0]
  5416. -100
  5417. [-100.0]
  5418. +100
  5419. [100.0]
  5420. 3.14159
  5421. [3.14159]
  5422. 6.02e23
  5423. [6.02e+23]
  5424. 1e-12
  5425. [1e-12]
  5426. # hex numbers
  5427. 100
  5428. [256]
  5429. FF
  5430. [255]
  5431. # fractions
  5432. 1/2
  5433. [0.5]
  5434. -3/4
  5435. [-0.75]
  5436. # mixed fractions
  5437. 1
  5438. [1]
  5439. 1/2
  5440. [0.5]
  5441. -3/4
  5442. [-0.75]
  5443. 1-3/4
  5444. [1.75]
  5445. # uuid
  5446. 12345678-1234-5678-1234-567812345678
  5447. [UUID('12345678-1234-5678-1234-567812345678')]
  5448. """
  5449. convertToInteger = tokenMap(int)
  5450. """
  5451. Parse action for converting parsed integers to Python int
  5452. """
  5453. convertToFloat = tokenMap(float)
  5454. """
  5455. Parse action for converting parsed numbers to Python float
  5456. """
  5457. integer = Word(nums).setName("integer").setParseAction(convertToInteger)
  5458. """expression that parses an unsigned integer, returns an int"""
  5459. hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int, 16))
  5460. """expression that parses a hexadecimal integer, returns an int"""
  5461. signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger)
  5462. """expression that parses an integer with optional leading sign, returns an int"""
  5463. fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction")
  5464. """fractional expression of an integer divided by an integer, returns a float"""
  5465. fraction.addParseAction(lambda t: t[0]/t[-1])
  5466. mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction")
  5467. """mixed integer of the form 'integer - fraction', with optional leading integer, returns float"""
  5468. mixed_integer.addParseAction(sum)
  5469. real = Regex(r'[+-]?(?:\d+\.\d*|\.\d+)').setName("real number").setParseAction(convertToFloat)
  5470. """expression that parses a floating point number and returns a float"""
  5471. sci_real = Regex(r'[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat)
  5472. """expression that parses a floating point number with optional
  5473. scientific notation and returns a float"""
  5474. # streamlining this expression makes the docs nicer-looking
  5475. number = (sci_real | real | signed_integer).streamline()
  5476. """any numeric expression, returns the corresponding Python type"""
  5477. fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat)
  5478. """any int or real number, returned as float"""
  5479. identifier = Word(alphas + '_', alphanums + '_').setName("identifier")
  5480. """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')"""
  5481. ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address")
  5482. "IPv4 address (``0.0.0.0 - 255.255.255.255``)"
  5483. _ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer")
  5484. _full_ipv6_address = (_ipv6_part + (':' + _ipv6_part) * 7).setName("full IPv6 address")
  5485. _short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6))
  5486. + "::"
  5487. + Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6))
  5488. ).setName("short IPv6 address")
  5489. _short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8)
  5490. _mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address")
  5491. ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address")
  5492. "IPv6 address (long, short, or mixed form)"
  5493. mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address")
  5494. "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)"
  5495. @staticmethod
  5496. def convertToDate(fmt="%Y-%m-%d"):
  5497. """
  5498. Helper to create a parse action for converting parsed date string to Python datetime.date
  5499. Params -
  5500. - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
  5501. Example::
  5502. date_expr = pyparsing_common.iso8601_date.copy()
  5503. date_expr.setParseAction(pyparsing_common.convertToDate())
  5504. print(date_expr.parseString("1999-12-31"))
  5505. prints::
  5506. [datetime.date(1999, 12, 31)]
  5507. """
  5508. def cvt_fn(s, l, t):
  5509. try:
  5510. return datetime.strptime(t[0], fmt).date()
  5511. except ValueError as ve:
  5512. raise ParseException(s, l, str(ve))
  5513. return cvt_fn
  5514. @staticmethod
  5515. def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
  5516. """Helper to create a parse action for converting parsed
  5517. datetime string to Python datetime.datetime
  5518. Params -
  5519. - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
  5520. Example::
  5521. dt_expr = pyparsing_common.iso8601_datetime.copy()
  5522. dt_expr.setParseAction(pyparsing_common.convertToDatetime())
  5523. print(dt_expr.parseString("1999-12-31T23:59:59.999"))
  5524. prints::
  5525. [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
  5526. """
  5527. def cvt_fn(s, l, t):
  5528. try:
  5529. return datetime.strptime(t[0], fmt)
  5530. except ValueError as ve:
  5531. raise ParseException(s, l, str(ve))
  5532. return cvt_fn
  5533. iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date")
  5534. "ISO8601 date (``yyyy-mm-dd``)"
  5535. iso8601_datetime = Regex(r'(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime")
  5536. "ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``"
  5537. uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID")
  5538. "UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)"
  5539. _html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress()
  5540. @staticmethod
  5541. def stripHTMLTags(s, l, tokens):
  5542. """Parse action to remove HTML tags from web page HTML source
  5543. Example::
  5544. # strip HTML links from normal text
  5545. text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
  5546. td, td_end = makeHTMLTags("TD")
  5547. table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
  5548. print(table_text.parseString(text).body)
  5549. Prints::
  5550. More info at the pyparsing wiki page
  5551. """
  5552. return pyparsing_common._html_stripper.transformString(tokens[0])
  5553. _commasepitem = Combine(OneOrMore(~Literal(",")
  5554. + ~LineEnd()
  5555. + Word(printables, excludeChars=',')
  5556. + Optional(White(" \t")))).streamline().setName("commaItem")
  5557. comma_separated_list = delimitedList(Optional(quotedString.copy()
  5558. | _commasepitem, default='')
  5559. ).setName("comma separated list")
  5560. """Predefined expression of 1 or more printable words or quoted strings, separated by commas."""
  5561. upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper()))
  5562. """Parse action to convert tokens to upper case."""
  5563. downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower()))
  5564. """Parse action to convert tokens to lower case."""
  5565. class _lazyclassproperty(object):
  5566. def __init__(self, fn):
  5567. self.fn = fn
  5568. self.__doc__ = fn.__doc__
  5569. self.__name__ = fn.__name__
  5570. def __get__(self, obj, cls):
  5571. if cls is None:
  5572. cls = type(obj)
  5573. if not hasattr(cls, '_intern') or any(cls._intern is getattr(superclass, '_intern', [])
  5574. for superclass in cls.__mro__[1:]):
  5575. cls._intern = {}
  5576. attrname = self.fn.__name__
  5577. if attrname not in cls._intern:
  5578. cls._intern[attrname] = self.fn(cls)
  5579. return cls._intern[attrname]
  5580. class unicode_set(object):
  5581. """
  5582. A set of Unicode characters, for language-specific strings for
  5583. ``alphas``, ``nums``, ``alphanums``, and ``printables``.
  5584. A unicode_set is defined by a list of ranges in the Unicode character
  5585. set, in a class attribute ``_ranges``, such as::
  5586. _ranges = [(0x0020, 0x007e), (0x00a0, 0x00ff),]
  5587. A unicode set can also be defined using multiple inheritance of other unicode sets::
  5588. class CJK(Chinese, Japanese, Korean):
  5589. pass
  5590. """
  5591. _ranges = []
  5592. @classmethod
  5593. def _get_chars_for_ranges(cls):
  5594. ret = []
  5595. for cc in cls.__mro__:
  5596. if cc is unicode_set:
  5597. break
  5598. for rr in cc._ranges:
  5599. ret.extend(range(rr[0], rr[-1] + 1))
  5600. return [unichr(c) for c in sorted(set(ret))]
  5601. @_lazyclassproperty
  5602. def printables(cls):
  5603. "all non-whitespace characters in this range"
  5604. return u''.join(filterfalse(unicode.isspace, cls._get_chars_for_ranges()))
  5605. @_lazyclassproperty
  5606. def alphas(cls):
  5607. "all alphabetic characters in this range"
  5608. return u''.join(filter(unicode.isalpha, cls._get_chars_for_ranges()))
  5609. @_lazyclassproperty
  5610. def nums(cls):
  5611. "all numeric digit characters in this range"
  5612. return u''.join(filter(unicode.isdigit, cls._get_chars_for_ranges()))
  5613. @_lazyclassproperty
  5614. def alphanums(cls):
  5615. "all alphanumeric characters in this range"
  5616. return cls.alphas + cls.nums
  5617. class pyparsing_unicode(unicode_set):
  5618. """
  5619. A namespace class for defining common language unicode_sets.
  5620. """
  5621. _ranges = [(32, sys.maxunicode)]
  5622. class Latin1(unicode_set):
  5623. "Unicode set for Latin-1 Unicode Character Range"
  5624. _ranges = [(0x0020, 0x007e), (0x00a0, 0x00ff),]
  5625. class LatinA(unicode_set):
  5626. "Unicode set for Latin-A Unicode Character Range"
  5627. _ranges = [(0x0100, 0x017f),]
  5628. class LatinB(unicode_set):
  5629. "Unicode set for Latin-B Unicode Character Range"
  5630. _ranges = [(0x0180, 0x024f),]
  5631. class Greek(unicode_set):
  5632. "Unicode set for Greek Unicode Character Ranges"
  5633. _ranges = [
  5634. (0x0370, 0x03ff), (0x1f00, 0x1f15), (0x1f18, 0x1f1d), (0x1f20, 0x1f45), (0x1f48, 0x1f4d),
  5635. (0x1f50, 0x1f57), (0x1f59,), (0x1f5b,), (0x1f5d,), (0x1f5f, 0x1f7d), (0x1f80, 0x1fb4), (0x1fb6, 0x1fc4),
  5636. (0x1fc6, 0x1fd3), (0x1fd6, 0x1fdb), (0x1fdd, 0x1fef), (0x1ff2, 0x1ff4), (0x1ff6, 0x1ffe),
  5637. ]
  5638. class Cyrillic(unicode_set):
  5639. "Unicode set for Cyrillic Unicode Character Range"
  5640. _ranges = [(0x0400, 0x04ff)]
  5641. class Chinese(unicode_set):
  5642. "Unicode set for Chinese Unicode Character Range"
  5643. _ranges = [(0x4e00, 0x9fff), (0x3000, 0x303f),]
  5644. class Japanese(unicode_set):
  5645. "Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges"
  5646. _ranges = []
  5647. class Kanji(unicode_set):
  5648. "Unicode set for Kanji Unicode Character Range"
  5649. _ranges = [(0x4E00, 0x9Fbf), (0x3000, 0x303f),]
  5650. class Hiragana(unicode_set):
  5651. "Unicode set for Hiragana Unicode Character Range"
  5652. _ranges = [(0x3040, 0x309f),]
  5653. class Katakana(unicode_set):
  5654. "Unicode set for Katakana Unicode Character Range"
  5655. _ranges = [(0x30a0, 0x30ff),]
  5656. class Korean(unicode_set):
  5657. "Unicode set for Korean Unicode Character Range"
  5658. _ranges = [(0xac00, 0xd7af), (0x1100, 0x11ff), (0x3130, 0x318f), (0xa960, 0xa97f), (0xd7b0, 0xd7ff), (0x3000, 0x303f),]
  5659. class CJK(Chinese, Japanese, Korean):
  5660. "Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range"
  5661. pass
  5662. class Thai(unicode_set):
  5663. "Unicode set for Thai Unicode Character Range"
  5664. _ranges = [(0x0e01, 0x0e3a), (0x0e3f, 0x0e5b),]
  5665. class Arabic(unicode_set):
  5666. "Unicode set for Arabic Unicode Character Range"
  5667. _ranges = [(0x0600, 0x061b), (0x061e, 0x06ff), (0x0700, 0x077f),]
  5668. class Hebrew(unicode_set):
  5669. "Unicode set for Hebrew Unicode Character Range"
  5670. _ranges = [(0x0590, 0x05ff),]
  5671. class Devanagari(unicode_set):
  5672. "Unicode set for Devanagari Unicode Character Range"
  5673. _ranges = [(0x0900, 0x097f), (0xa8e0, 0xa8ff)]
  5674. pyparsing_unicode.Japanese._ranges = (pyparsing_unicode.Japanese.Kanji._ranges
  5675. + pyparsing_unicode.Japanese.Hiragana._ranges
  5676. + pyparsing_unicode.Japanese.Katakana._ranges)
  5677. # define ranges in language character sets
  5678. if PY_3:
  5679. setattr(pyparsing_unicode, u"العربية", pyparsing_unicode.Arabic)
  5680. setattr(pyparsing_unicode, u"中文", pyparsing_unicode.Chinese)
  5681. setattr(pyparsing_unicode, u"кириллица", pyparsing_unicode.Cyrillic)
  5682. setattr(pyparsing_unicode, u"Ελληνικά", pyparsing_unicode.Greek)
  5683. setattr(pyparsing_unicode, u"עִברִית", pyparsing_unicode.Hebrew)
  5684. setattr(pyparsing_unicode, u"日本語", pyparsing_unicode.Japanese)
  5685. setattr(pyparsing_unicode.Japanese, u"漢字", pyparsing_unicode.Japanese.Kanji)
  5686. setattr(pyparsing_unicode.Japanese, u"カタカナ", pyparsing_unicode.Japanese.Katakana)
  5687. setattr(pyparsing_unicode.Japanese, u"ひらがな", pyparsing_unicode.Japanese.Hiragana)
  5688. setattr(pyparsing_unicode, u"한국어", pyparsing_unicode.Korean)
  5689. setattr(pyparsing_unicode, u"ไทย", pyparsing_unicode.Thai)
  5690. setattr(pyparsing_unicode, u"देवनागरी", pyparsing_unicode.Devanagari)
  5691. class pyparsing_test:
  5692. """
  5693. namespace class for classes useful in writing unit tests
  5694. """
  5695. class reset_pyparsing_context:
  5696. """
  5697. Context manager to be used when writing unit tests that modify pyparsing config values:
  5698. - packrat parsing
  5699. - default whitespace characters.
  5700. - default keyword characters
  5701. - literal string auto-conversion class
  5702. - __diag__ settings
  5703. Example:
  5704. with reset_pyparsing_context():
  5705. # test that literals used to construct a grammar are automatically suppressed
  5706. ParserElement.inlineLiteralsUsing(Suppress)
  5707. term = Word(alphas) | Word(nums)
  5708. group = Group('(' + term[...] + ')')
  5709. # assert that the '()' characters are not included in the parsed tokens
  5710. self.assertParseAndCheckLisst(group, "(abc 123 def)", ['abc', '123', 'def'])
  5711. # after exiting context manager, literals are converted to Literal expressions again
  5712. """
  5713. def __init__(self):
  5714. self._save_context = {}
  5715. def save(self):
  5716. self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
  5717. self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS
  5718. self._save_context[
  5719. "literal_string_class"
  5720. ] = ParserElement._literalStringClass
  5721. self._save_context["packrat_enabled"] = ParserElement._packratEnabled
  5722. self._save_context["packrat_parse"] = ParserElement._parse
  5723. self._save_context["__diag__"] = {
  5724. name: getattr(__diag__, name) for name in __diag__._all_names
  5725. }
  5726. self._save_context["__compat__"] = {
  5727. "collect_all_And_tokens": __compat__.collect_all_And_tokens
  5728. }
  5729. return self
  5730. def restore(self):
  5731. # reset pyparsing global state
  5732. if (
  5733. ParserElement.DEFAULT_WHITE_CHARS
  5734. != self._save_context["default_whitespace"]
  5735. ):
  5736. ParserElement.setDefaultWhitespaceChars(
  5737. self._save_context["default_whitespace"]
  5738. )
  5739. Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
  5740. ParserElement.inlineLiteralsUsing(
  5741. self._save_context["literal_string_class"]
  5742. )
  5743. for name, value in self._save_context["__diag__"].items():
  5744. setattr(__diag__, name, value)
  5745. ParserElement._packratEnabled = self._save_context["packrat_enabled"]
  5746. ParserElement._parse = self._save_context["packrat_parse"]
  5747. __compat__.collect_all_And_tokens = self._save_context["__compat__"]
  5748. def __enter__(self):
  5749. return self.save()
  5750. def __exit__(self, *args):
  5751. return self.restore()
  5752. class TestParseResultsAsserts:
  5753. """
  5754. A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
  5755. """
  5756. def assertParseResultsEquals(
  5757. self, result, expected_list=None, expected_dict=None, msg=None
  5758. ):
  5759. """
  5760. Unit test assertion to compare a ParseResults object with an optional expected_list,
  5761. and compare any defined results names with an optional expected_dict.
  5762. """
  5763. if expected_list is not None:
  5764. self.assertEqual(expected_list, result.asList(), msg=msg)
  5765. if expected_dict is not None:
  5766. self.assertEqual(expected_dict, result.asDict(), msg=msg)
  5767. def assertParseAndCheckList(
  5768. self, expr, test_string, expected_list, msg=None, verbose=True
  5769. ):
  5770. """
  5771. Convenience wrapper assert to test a parser element and input string, and assert that
  5772. the resulting ParseResults.asList() is equal to the expected_list.
  5773. """
  5774. result = expr.parseString(test_string, parseAll=True)
  5775. if verbose:
  5776. print(result.dump())
  5777. self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)
  5778. def assertParseAndCheckDict(
  5779. self, expr, test_string, expected_dict, msg=None, verbose=True
  5780. ):
  5781. """
  5782. Convenience wrapper assert to test a parser element and input string, and assert that
  5783. the resulting ParseResults.asDict() is equal to the expected_dict.
  5784. """
  5785. result = expr.parseString(test_string, parseAll=True)
  5786. if verbose:
  5787. print(result.dump())
  5788. self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)
  5789. def assertRunTestResults(
  5790. self, run_tests_report, expected_parse_results=None, msg=None
  5791. ):
  5792. """
  5793. Unit test assertion to evaluate output of ParserElement.runTests(). If a list of
  5794. list-dict tuples is given as the expected_parse_results argument, then these are zipped
  5795. with the report tuples returned by runTests and evaluated using assertParseResultsEquals.
  5796. Finally, asserts that the overall runTests() success value is True.
  5797. :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests
  5798. :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]
  5799. """
  5800. run_test_success, run_test_results = run_tests_report
  5801. if expected_parse_results is not None:
  5802. merged = [
  5803. (rpt[0], rpt[1], expected)
  5804. for rpt, expected in zip(run_test_results, expected_parse_results)
  5805. ]
  5806. for test_string, result, expected in merged:
  5807. # expected should be a tuple containing a list and/or a dict or an exception,
  5808. # and optional failure message string
  5809. # an empty tuple will skip any result validation
  5810. fail_msg = next(
  5811. (exp for exp in expected if isinstance(exp, str)), None
  5812. )
  5813. expected_exception = next(
  5814. (
  5815. exp
  5816. for exp in expected
  5817. if isinstance(exp, type) and issubclass(exp, Exception)
  5818. ),
  5819. None,
  5820. )
  5821. if expected_exception is not None:
  5822. with self.assertRaises(
  5823. expected_exception=expected_exception, msg=fail_msg or msg
  5824. ):
  5825. if isinstance(result, Exception):
  5826. raise result
  5827. else:
  5828. expected_list = next(
  5829. (exp for exp in expected if isinstance(exp, list)), None
  5830. )
  5831. expected_dict = next(
  5832. (exp for exp in expected if isinstance(exp, dict)), None
  5833. )
  5834. if (expected_list, expected_dict) != (None, None):
  5835. self.assertParseResultsEquals(
  5836. result,
  5837. expected_list=expected_list,
  5838. expected_dict=expected_dict,
  5839. msg=fail_msg or msg,
  5840. )
  5841. else:
  5842. # warning here maybe?
  5843. print("no validation for {!r}".format(test_string))
  5844. # do this last, in case some specific test results can be reported instead
  5845. self.assertTrue(
  5846. run_test_success, msg=msg if msg is not None else "failed runTests"
  5847. )
  5848. @contextmanager
  5849. def assertRaisesParseException(self, exc_type=ParseException, msg=None):
  5850. with self.assertRaises(exc_type, msg=msg):
  5851. yield
  5852. if __name__ == "__main__":
  5853. selectToken = CaselessLiteral("select")
  5854. fromToken = CaselessLiteral("from")
  5855. ident = Word(alphas, alphanums + "_$")
  5856. columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
  5857. columnNameList = Group(delimitedList(columnName)).setName("columns")
  5858. columnSpec = ('*' | columnNameList)
  5859. tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
  5860. tableNameList = Group(delimitedList(tableName)).setName("tables")
  5861. simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables")
  5862. # demo runTests method, including embedded comments in test string
  5863. simpleSQL.runTests("""
  5864. # '*' as column list and dotted table name
  5865. select * from SYS.XYZZY
  5866. # caseless match on "SELECT", and casts back to "select"
  5867. SELECT * from XYZZY, ABC
  5868. # list of column names, and mixed case SELECT keyword
  5869. Select AA,BB,CC from Sys.dual
  5870. # multiple tables
  5871. Select A, B, C from Sys.dual, Table2
  5872. # invalid SELECT keyword - should fail
  5873. Xelect A, B, C from Sys.dual
  5874. # incomplete command - should fail
  5875. Select
  5876. # invalid column name - should fail
  5877. Select ^^^ frox Sys.dual
  5878. """)
  5879. pyparsing_common.number.runTests("""
  5880. 100
  5881. -100
  5882. +100
  5883. 3.14159
  5884. 6.02e23
  5885. 1e-12
  5886. """)
  5887. # any int or real number, returned as float
  5888. pyparsing_common.fnumber.runTests("""
  5889. 100
  5890. -100
  5891. +100
  5892. 3.14159
  5893. 6.02e23
  5894. 1e-12
  5895. """)
  5896. pyparsing_common.hex_integer.runTests("""
  5897. 100
  5898. FF
  5899. """)
  5900. import uuid
  5901. pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
  5902. pyparsing_common.uuid.runTests("""
  5903. 12345678-1234-5678-1234-567812345678
  5904. """)